<?php

use Qiboot\Sms;

/* 系统公共函数库 */



/**

 * 清除设置的session

 *  

 */

function clear_session() {

    session('rep_status', null);

    session('rep_msg', null);

}



/**

 * 设置跳转页面URL

 *  

 * @param string $url 页面URL

 */

function set_redirect_url($url) {

    cookie('redirect_url', $url);

}



/**

 * 获取跳转页面URL

 *  

 * @return string 跳转页URL

 */

function get_redirect_url() {

    return cookie('redirect_url');

}



/**

 * 获取或设置配置项的值

 *  

 * @param string $name 配置项名称

 * @param string $value 配置项的值

 * @return mixed

 */

function config($name, $value = null,$shop_id = SHOP_ID) {

    $shop_id = intval($shop_id);

    static $allConfig = array();

    $res = null;



    if (isset($value)) {

        $res = M('Config')->add(array('config_name' => $name, 'shop_id' => $shop_id, 'config_value' => $value), array(), true);

        $allConfig[$shop_id] = array();

    } else {
 
        // 查询全部以免每次都查询

        if(!isset($allConfig[$shop_id]) || !$allConfig[$shop_id]){

            $shopConfig = M('Config')->where(array('shop_id' => $shop_id))->getField('config_name,config_value', true);

            $allConfig[$shop_id] = $shopConfig;

        }

        if(is_null($name)){

            return $allConfig[$shop_id];

        }

        isset($allConfig[$shop_id][$name]) && $res = $allConfig[$shop_id][$name];

    }



    return $res;

}

 

/**

 * 获取或设置缓存

 *  

 * @param string $name 缓存名称

 * @param string $value 缓存值

 * @return mixed

 */

function cache($name, $value = null,$shop_id = SHOP_ID) {

    $cache_name = $name . $shop_id;

    if (isset($value)) return S($cache_name, $value);

    else return S($cache_name);

}



/**

 * 获取紧缩后的上级id

 * @param $uid 当前用户id 

 * @return string  上级分销商id 

 * @author lius

 */

function get_fx_pid($uid){

    if(!$uid){

        return false;

    }

    // file_put_contents('aa1',$uid);

    $User = D('User');

    $date = date('Y-m-d',time());//.' AND agent_rank_id>0 AND is_agent>0 AND agent_type>0 AND tighten_date>="'.$date.'"')

    // $id = $User->where('agent_rank_id>0 AND is_agent>0 AND agent_type>0 AND tighten_date>="'.$date.'"')->getField('superior_user_id');

    $pid = $User->where('user_id = '.$uid )->getField('superior_user_id');

    // file_put_contents('aa2',$pid);

    if(empty($pid)) return 0;

    $id = $User->where('user_id = '.$pid .' AND agent_rank_id>0 AND is_agent>0 AND agent_type>0 AND "'.$date.'">=strat_tighten AND tighten_date>="'.$date.'"')->getField('user_id');

    // file_put_contents('aa3', $User->_sql());

    if($id) return $id;

    // file_put_contents('aa3',$id);

    return get_fx_pid($pid);

 /*   // if(!$info) return false;

    // if(!$info['superior_user_id']) return false;

    // $id=$User->where('user_id='.$info['superior_user_id'] .' AND agent_rank_id>0 AND is_agent>0 AND agent_type>0 AND tighten_date>="'.$date.'"')->getField('user_id');

    // if($id) return $id;

    // if(!$info['top_user_id']) return false;

    // $id=$User->where('user_id='.$info['top_user_id'] .' AND agent_rank_id>0 AND is_agent>0 AND agent_type>0 AND tighten_date>="'.$date.'"')->getField('user_id');

    // if($id) return $id;

    // if(!$info['three_user_id']) return false;

    // $id=$User->where('user_id='.$info['three_user_id'] .' AND agent_rank_id>0 AND is_agent>0 AND agent_type>0 AND tighten_date>="'.$date.'"')->getField('user_id');

    // if($id) {

    //     return $id;

    // }else{

    //     $id=get_fx_pid($info['three_user_id']);

    //     return $id;

    // }*/

}

/**

 * 时间戳格式化

 * @param int $time 时间戳

 * @param string $format 格式

 * @return string 完整的时间显示

 *  

 */

function time_format($time = NULL,$format='Y-m-d H:i:s') {

    $time = $time === NULL ? NOW_TIME : intval($time);

    if ($time === 0) return '--';

    return date($format, $time);

}

/**

 * 对象转成数组，用于TOP API相关的操作

 *  

 */

function object_to_array($obj) {

    $_arr = is_object($obj) ? get_object_vars($obj) : $obj;

    $arr=array();

    foreach ($_arr as $key => $val)

    {

        $val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val;

        $arr[$key] = $val;

    }

    return $arr;

}

/**

 * 浮点数格式化(去除不用的小数点和0)

 *  

 * @param float $float 浮点数

 * @return float

 */

function float_format($float) {

    return rtrim(rtrim($float, 0), '.');

}



/**

 * 检测用户是否登录

 * @return integer 0-未登录，大于0-当前登录用户ID

 *  

 */

function is_login(){

    $user = session('user_auth');

    if (empty($user)) {

        return 0;

    } else {

        return session('user_auth_sign') == data_auth_sign($user) ? $user['sid'] : 0;

    }

}



/**

 * 检测用户是否通过登陆验证

 * @return integer 0-未登录，大于0-当前登录用户ID

 *  

 */

function is_login_auth($seller_id = SID){

    $user = cookie('login_auth');

    if (empty($user)) {

        return 0;

    } else {

        return ((cookie('login_auth_sign') == data_auth_sign($user)) && ($user['sid'] == $seller_id)) ? $user['auth'] : 0;

    }

}



/**

 * 检测用户是否登录

 * @return integer 0-未登录，大于0-当前登录用户ID

 *  

 */

function is_admin(){

    $user = session('user_auth');

    if (empty($user)) {

        return 0;

    } else {

        if (session('user_auth_sign') == data_auth_sign($user) && isset($user['aid'])) {

            return $user['aid'];

        } else {

            return 0;

        }

    }

}

/**

 * 检测用户是否登录

 * @return integer 0-未登录，大于0-当前登录用户ID

 *  

 */

function is_priv(){

    $user = session('user_auth');

    if (empty($user)) {

        return 0;

    } else {

        if (session('user_auth_sign') == data_auth_sign($user) && isset($user['priv_str'])) {

            return $user['priv_str'];

        } else {

            return 0;

        }

    }

}

/**

 * 检测验证码

 * @param  string $code 验证码

 * @param  int $id 验证码ID

 * @return bool 检测结果

 *  

 */

function check_verify($code, $id = 1) {

    $verify = new \Think\Verify();

    return $verify->check($code, $id);

}



/**

 * 数据签名认证

 * @param  array  $data 被认证的数据

 * @return string       签名

 *  

 */

function data_auth_sign($data) {

    //数据类型检测

    if(!is_array($data)){

        $data = (array)$data;

    }

    ksort($data); //排序

    $code = http_build_query($data); //url编码并生成query字符串

    $sign = sha1($code); //生成签名

    return $sign;

}



/**
 * 上传图片（OSS）
 * @author Zy
 * @param string $fileBoxName file输入框的名称
 * @return array
 */
function uploadImg($fileBoxName = 'imageUp') {
    if(!empty($_FILES[$fileBoxName]['name'])){

        $allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        // 文件后缀
        $pathinfo = pathinfo($_FILES[$fileBoxName]['name']);
        $extension =  $pathinfo['extension'];
        if (!in_array(strtolower($extension), $allowExts)) {
            // 兼容vivo
            if (strpos($pathinfo['filename'], 'image%') === 0) {
                $extension = 'jpg';
            } else {
                return false;
            }
        }

        $bucket = C('OSS_BUCKET');
        $endpoint= C('DEFAULT_OSS_HOST');
        $object = UPLOAD_PATH . date(C('DATE_FORMAT'), time()) . '/' . uniqid() . '.' . $extension;
        $file_path = $_FILES[$fileBoxName]['tmp_name'];

        // 判断是否使用新接口
        if (C('DEFAULT_OSS_HOST') == 'oss-cn-hangzhou.aliyuncs.com1') {
            $ossClient = new \OSS\OssClient(C('OSS_ACCESS_ID'), C('OSS_ACCESS_KEY'), C('DEFAULT_OSS_HOST'));
            $response = $ossClient->uploadFile($bucket, $object, $file_path);
            if (isset($response['oss-request-url']) && $response['oss-request-url']) {
                $pic_url = $response['oss-request-url'];
                $pt = '/.*' . C('DEFAULT_OSS_HOST') . '(.*)/';
            }
        } else {
            vendor('Aliyun.OSS.sdk');
            $ALIOSS = new \ALIOSS();
            $response = $ALIOSS->upload_file_by_file($bucket, $object, $file_path);
            $response = get_object_vars($response);
            if (isset($response['header']['x-oss-request-url']) && $response['header']['x-oss-request-url']) {
                $pic_url = $response['header']['x-oss-request-url'];
                $pt = '/.*' . C('OSS_BUCKET') . '(.*)/';
            }
        }

        if ($pic_url) {
            if (preg_match($pt, $pic_url, $match)) {
                $data['pic_url'] = C('IMG_URL') . $match[1];
                $data['pic_url'] = str_replace($endpoint,'',$data['pic_url']);

                // 判断是否需要压缩
                $size = getimagesize($file_path);
                if ($size[0] > 640 && strtolower($extension) != 'gif') {
                    $data['pic_url'] .= '@!' . C('IMG_STYLE');
                }

                //文件初始名称
                $data['file_name'] = $_FILES[$fileBoxName]['name'];
                return $data;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    return false;
}

/*
 * 上传多个图片
 * @author zc
 */
function uploadImgs($fileBoxName='imageUp'){

    if(!empty($_FILES[$fileBoxName]['name'])){

        $allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型

        foreach($_FILES[$fileBoxName]['name'] as $k=>$v){
            // 文件后缀
            $pathinfo = pathinfo($v);
            $extension = $pathinfo['extension'];
            if (in_array(strtolower($extension), $allowExts)){
                $bucket = C('OSS_BUCKET');
                $endpoint= C('DEFAULT_OSS_HOST');
                $object = UPLOAD_PATH . date(C('DATE_FORMAT'), time()) . '/' . uniqid() . '.' . $extension;
                $file_path = $_FILES[$fileBoxName]['tmp_name'][$k];


                // 判断是否使用新接口
                if (C('DEFAULT_OSS_HOST') == 'oss-cn-hangzhou.aliyuncs.com1') {
                    $ossClient = new \OSS\OssClient(C('OSS_ACCESS_ID'), C('OSS_ACCESS_KEY'), C('DEFAULT_OSS_HOST'));
                    $response = $ossClient->uploadFile($bucket, $object, $file_path);
                    if (isset($response['oss-request-url']) && $response['oss-request-url']) {
                        $pic_url = $response['oss-request-url'];
                        $pt = '/.*' . C('DEFAULT_OSS_HOST') . '(.*)/';
                    }
                } else {
                    vendor('Aliyun.OSS.sdk');
                    $ALIOSS = new \ALIOSS();
                    $response = $ALIOSS->upload_file_by_file($bucket, $object, $file_path);
                    $response = get_object_vars($response);
                    if (isset($response['header']['x-oss-request-url']) && $response['header']['x-oss-request-url']) {
                        $pic_url = $response['header']['x-oss-request-url'];
                        $pt = '/.*' . C('OSS_BUCKET') . '(.*)/';
                    }
                }

                if ($pic_url) {
                    if (preg_match($pt, $pic_url, $match)) {
                        $data[$k]['pic_url'] = C('IMG_URL') . $match[1];
                        $data[$k]['pic_url'] = str_replace($endpoint,'',$data[$k]['pic_url']);
                      
                        // 判断是否需要压缩
                        $size = getimagesize($file_path);
                        if ($size[0] > 640 && strtolower($extension) != 'gif') {
                            $data[$k]['pic_url'] .= '@!' . C('IMG_STYLE');
                        }
                    }
                }
            }

        }
        return $data;
    }
    return false;
}

/**
 * 上传本地文件到OSS
 * @author zc
 */
function UploadImgOss($file_path){
    $allowExts  = array('jpg', 'gif', 'png', 'jpeg','tbi');// 设置附件上传类型
    // 文件后缀
    $pathinfo = pathinfo($file_path);
    $extension =  $pathinfo['extension'];
    if (!in_array(strtolower($extension), $allowExts)) return false;

    $bucket = C('OSS_BUCKET');
    $endpoint= C('DEFAULT_OSS_HOST');
    if($extension == 'tbi') $extension = 'jpg';
    $object = UPLOAD_PATH . date(C('DATE_FORMAT'), time()) . '/' . uniqid() . '.' . $extension;


    // 判断是否使用新接口
    if (C('DEFAULT_OSS_HOST') == 'oss-cn-hangzhou.aliyuncs.com') {
        $ossClient = new \OSS\OssClient(C('OSS_ACCESS_ID'), C('OSS_ACCESS_KEY'), C('DEFAULT_OSS_HOST'));
        $response = $ossClient->uploadFile($bucket, $object, $file_path);
        if (isset($response['oss-request-url']) && $response['oss-request-url']) {
            $pic_url = $response['oss-request-url'];
            $pt = '/.*' . C('DEFAULT_OSS_HOST') . '(.*)/';
        }
    } else {
        vendor('Aliyun.OSS.sdk');
        $ALIOSS = new \ALIOSS();
        $response = $ALIOSS->upload_file_by_file($bucket, $object, $file_path);
        $response = get_object_vars($response);
        if (isset($response['header']['x-oss-request-url']) && $response['header']['x-oss-request-url']) {
            $pic_url = $response['header']['x-oss-request-url'];
            $pt = '/.*' . C('OSS_BUCKET') . '(.*)/';
        }
    }

    if ($pic_url) {
        if (preg_match($pt, $pic_url, $match)) {
            $img_url = C('IMG_URL') . $match[1];
            $img_url = str_replace($endpoint,'',$img_url);  
            // 判断是否需要压缩
            $size = getimagesize($file_path);
            if ($size[0] > 640 && strtolower($extension) != 'gif') {
                $img_url .= '@!' . C('IMG_STYLE');
            }
            //文件初始名称
            return $img_url;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

/**

 * 判断是否通过手机访问

 *  

 * @return bool

 */

function is_mob() {

    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);

    if ((strpos($agent, 'mobile') === false) && (strpos($agent, 'micromessenger') === false) && (strpos($agent, 'yzs.wxfenxiao') === false)) return false;

    else return true;

}



//判断是否ＰＣ端打开

function isPC(){

    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);

    //获取系统类型

    $is_pc = (strpos($agent, 'windows nt') || strpos($agent, 'macintosh')) ? true : false;

    return $is_pc;

}



/**

 * 非常规MD5加密方法

 * @param string $str 要加密的字符串

 * @param string $key 增加字符

 * @return string 加密后的字符串

 *  

 */

function think_md5($str, $key = 'Think') {

    return '' === $str ? '' : md5(sha1($str) . $key);

}

/**

 * 获取买家购买地址

 *  

 */

function getUserAddress($address_id){

    $UserAddress = M('UserAddress');

    $info = $UserAddress->where('address_id = ' . $address_id)->field('address_id, name, mobile, phone, province_id, city_id, area_id, address, zip')->find();



    $Province = M('Province');

    $City = M('City');

    $Area = M('Area');



    if ($info) {

        $info['province'] = $Province->where('province_id = ' . $info['province_id'])->getField('province_name');

        $info['city'] = $City->where('city_id = ' . $info['city_id'])->getField('city_name');

        $info['area'] = $Area->where('area_id = ' . $info['area_id'])->getField('area_name');

    }



    return array('address' => $info);

}



function apiSing($params){

    if(empty($params)){

        return false;

    }

    if(isset($params['auth_code'])){

        $before = substr($params['auth_code'],0,7);

        $after = substr($params['auth_code'],15,16);

    }

    $sign = '';

    ksort($params);

    foreach($params as $key => $rs){

        if(is_array($rs)){

            ksort($rs);

            foreach($rs as $k => $v){

                $sign .= $k.'='.$v.'&';

            }

        }else{

            $sign .= $key.'='.$rs.'&';

        }

    }

    $sign = trim($sign,'&');

    return isset($before)&&isset($after)?strtoupper(md5($before.$sign.$after)):strtoupper(md5($sign));

}



/**

 * 发送短信

 *  

 * @param int $mobile 接收人的手机号

 * @param string $text 短信内容

 * @param int $type 短信通道（1：通知通道；2：营销通道; 3:可修改短信签名）

 * @return bool

 */

function send_sms($strMobile,$content, $type=1){

            $text   = preg_replace('/<a href=[\\\]?"([^>]*)[\\\]?"[^>]*>(.*)<\/a>/isU', "$2" . "$1", $content);

            $text    = str_replace('【','[',$text);

            $content = str_replace('】',']',$text);

 

            $url  = 'http://sms.bamikeji.com:8890/mtPort/mt/normal/send?';

            // $data = "uid=%s&passwd=%s&phonelist=%s&content=%s&otime=";

            // $uid  = "tengmeng"; // 18058489911 "13580400999"; //yuntao001 gongsheng  13580400999

            // $pwd  = "8844080"; //hkdsy412 wd55dw clx198198

            $tos  = $strMobile;

            // file_put_contents('smst.txt',$tos);

            $content  = $content.SMS_SIGN;

            // file_put_contents('smsc.txt',$content);

            $msg = urlencode($content);

            $data = 'uid='.SMS_UID.'&passwd='.SMS_PWD.'&phonelist='.$tos.'&content='.$msg.'&otime=';

            // file_put_contents('smsd.txt',$data);

            $r_data = $url.$data;

            // file_put_contents('sms.txt',json_encode($r_date));

            $string = file_get_contents($r_data);

            // file_put_contents('sms1.txt',json_encode($string));

            // $xml = simplexml_load_string($string);

            // file_put_contents('smsx.txt',$xml);

            





    // $url = "http://sms.bamikeji.com:8890/mtPort/mt/normal/send?uid=".$uid."&passwd=".$pwd."&phonelist=".$Mobile."&content=".$content;

    // $html = file_get_contents($url);



            if($string['success']) 

            {

            return true;

            }

            else

            {

            return false;

            } 

}      

    

 

function send_bksms($mobile, $text, $type=3,$shop_id=SHOP_ID) {

    // 转换短信中的超链接

    $text = preg_replace('/<a href=[\\\]?"([^>]*)[\\\]?"[^>]*>(.*)<\/a>/isU', "$2" . "$1", $text);

    $text = str_replace('【','[',$text);

    $text = str_replace('】',']',$text);

    if ($type == 3) {

        $cdkey = '6SDK-EMY-6666-RJRSK';

        $password = '854468';

        $sessionKey = '450096';

        import('Vendor.YiMei.Client');

        $client = new \Client('http://sdktaows.eucp.b2m.cn:8080/sdk/SDKService', $cdkey, $password, $sessionKey);



        $sms_sign = config('sms_sign',null,$shop_id);

        $sms_sign = is_null($sms_sign) ? C('SMS_SIGN') : $sms_sign;

        if (!$sms_sign) $sms_sign = '微信分销';



        $message = "【" . $sms_sign . "】" . $text . ' 退订回复TD';



        $res = $client->sendSMS(array($mobile),$message);

        if ($res !== '0') return false;

        return true;

    } elseif ($type == 2) {

        $cdkey = '6SDK-EMY-6688-RCYQT';

        $password = '19881225';

        $url = 'http://sdktaows.eucp.b2m.cn:8080/sdkproxy/sendsms.action';

        $text .= ' 退订回复TD';

    } else {

        $cdkey = '6SDK-EMY-6688-KHRNN';

        $password = '360123360';

        $url = 'http://sdk4report.eucp.b2m.cn:8080/sdkproxy/sendsms.action';

    }

    $data = array('cdkey'=>$cdkey, 'password'=>$password, 'phone'=>$mobile, 'message'=>$text);

    $res = curl($url, $data);

    $res = json_decode(json_encode(simplexml_load_string($res)));

    if ($res->error) return false;

    else return true;

}



/**

 * 阿里短信接口

 *  

 */

function ali_send_sms($mobile,$code){

    $url_gateway = 'http://sms.tmallshop.cn/api/gateway?';

    $app_key = M('AcpConfig')->where('config_name = "app_key_sms"')->getField('config_value');

    $app_secert = M('AcpConfig')->where('config_name = "app_sercet_sms"')->getField('config_value');

    $params = array(

        'method' => 'send_sms',

        'app_key' => $app_key,

        'timestamp' => time(),

        'sms_param' => array('code' => (string)$code),

        'rec_num' => $mobile

    );



    $params['sign'] = sign($params, $app_secert);



    $url_gateway .= 'code=' . urlencode(encrypt($params));



    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url_gateway);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $res = curl_exec($ch);

    curl_close($ch);

    $results = json_decode($res,true);

    $result = $results['alibaba_aliqin_ta_sms_num_send_response']['result']['success'];

    if(!$result){

        file_put_contents('./Upload/log/ali_sms.log','mobile:'.$mobile.'返回错误'.$res.",create_time:".date('Y-m-d H:i:s',time())."\n",FILE_APPEND);

    }

    return $result;

}



function sign($params, $appSecret)

{

    if(isset($params['sign'])) {

        unset($params['sign']);

    }

    ksort($params);

    $paramsStr = '';

    foreach($params as $key => $value) {

        if(is_array($value)) {

            ksort($value);

            foreach($value as $k => $v) {

                $paramsStr .= $k . $v;

            }

        } else {

            $paramsStr .= $key . $value;

        }

    }

    $paramsStr = $appSecret . $paramsStr . $appSecret;

    return strtoupper(md5($paramsStr));

}



function curl($url, $postFields = null){

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_FAILONERROR, false);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);



    //https 请求

    if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

//      curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, 'rsa_rc4_128_sha');

    }



    if (is_array($postFields) && 0 < count($postFields))

    {

        $postBodyString = "";

        $postMultipart = false;

        foreach ($postFields as $k => $v)

        {

            if("@" != substr($v, 0, 1))//判断是不是文件上传

            {

                $postBodyString .= "$k=" . urlencode($v) . "&";

            }

            else//文件上传用multipart/form-data，否则用www-form-urlencoded

            {

                $postMultipart = true;

            }

        }

        unset($k, $v);

        curl_setopt($ch, CURLOPT_POST, true);

        if ($postMultipart)

        {

            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

        }

        else

        {

            curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));

        }

    }elseif ($postFields) {

        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

    }

    $reponse = curl_exec($ch);

    if (curl_errno($ch))

    {

//        throw new Exception(curl_error($ch),0);

    }

    else

    {

        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if (200 !== $httpStatusCode)

        {

//            throw new Exception($reponse,$httpStatusCode);

        }

    }

    curl_close($ch);

    return $reponse;

}



/**

 * 判断是否为手机号

 *  

 * @param int $mobile 传入的字符串

 * @return bool

 */

function is_mobile($mobile) {

    return preg_match('/^1[345789]{1}\d{9}$/', $mobile);

}



/**

 * 判断email格式是否正确

 *  

 * @param string $email

 * @return bool

 */

function is_email($email) {

    return preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/', $email);

}



/**

 * 判断生日格式是否正确

 *  

 * @param string $birthday

 * @return bool

 */

function is_birthday($birthday) {

    return preg_match('/(\d){4}-(\d){2}-(\d){2}/', $birthday);

}



/**

 * 判断密码格式是否正确

 *  

 * @param string $password

 * @return bool

 */

function is_password($password) {

    return preg_match('/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,32}$/', $password);

}



/**

 * 判断邮政编码是否正确

 *  

 * @param string $zip

 * @return bool

 */

function is_zip($zip) {

    return preg_match('/^\d{6}$/', $zip);

}



/**

 * 判断身份证号是否正确

 *  

 * @param string $id_card

 * @return bool

 */

function is_id_card($id_card) {

    return preg_match('/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/', $id_card);

}



/**

 * 验证用户身份证,获取用户信息

 * @zhangcheng

 */

function get_id_card($id_card,$type='json'){

    if(empty($id_card)){

        return false;

    }

    $appkey = '25092';

    $sign = '0e28ac29461d2a5b8ed881d0feb4056c';

    $url='http://api.k780.com:88/?app=idcard.get&idcard='.$id_card.'&appkey='.$appkey.'&sign='.$sign.'&format='.$type;

    $data = file_get_contents($url);

    $cdata = json_decode($data,true);

    if($cdata['success'] == 0){         

        return false;

    }else{

        return $data;

    }

    // $ch = curl_init();

    // $url = 'http://apis.baidu.com/netpopo/idcard/query1?idcard=41272519800102067x';

    // $header = array(

    //     'apikey: d8ad6ca1ed124b594a657e1edc3229b1',

    // );

    // // 添加apikey到header

    // curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);

    // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // // 执行HTTP请求

    // curl_setopt($ch , CURLOPT_URL , $url);

    // $res = curl_exec($ch);

    // $data=json_decode($data,true);

    // if($data['status']==0 ){

    //     return $res;

    // }else{

    //     return $res;

    // }



    //d8ad6ca1ed124b594a657e1edc3229b1

}

/**

* @param $astr 截取出的地区字符串

* @param $m 

* @return $astr 返回地区编码

* @author lius

*//*

function getAreaId($att,$citynm='',$simcall=''){

    if(strstr($att,'北京')){

        $data['pid'] = 110000;

        $data['cid'] = 110100;

        goto a;

    }else if(strstr($att,'上海')){

        $data['pid'] = 310000;

        $data['cid'] = 310100;

        goto a;

    }else if(strstr($att,'天津')){

        $data['pid'] = 120000;

        $data['cid'] = 120111;

        goto a;

    }else if(strstr($att,'重庆')){

        $data['pid'] = 500000;

        $data['cid'] = 500100;

        goto a;

    }else if(strstr($att,'自治区')){

        $a1 = strpos($att,'自治区');

        if(!$a1) $a1=strpos($att,' ');

    }else{

        $a1 = strpos($att,'省');

        file_put_contents('sareea',$a1);

        if(!$a1) $a1=strpos($att,' ');

    }

    $name = substr($att,0,$a1-1);

    $pwhere['province_name']=array('like',$name.'%') ;

    $data['pid'] = M('Province')->where($pwhere['province_name'])->cache(true)->getField('province_id');

    $att2 = substr($att,$a1); 

    if(strstr($att,'神农架')){

        $data['cid'] = 429021;

        goto a;

    }

    $a2 = strpos($att2,'市');

    if(!$a2) $a2=strpos($att2,'自治州');

    if(!$a2) $a2=strpos($att2,'地区');

    if(!$a2) $a2=strpos($att2,'盟');

    $name = substr($att2,0,$a2-1);

    $cwhere['city_name']=array('like',$name.'%') ;

    $cwhere['parent_id']=$data['pid'];

    $data['cid'] = M('City')->where($where['city_name'])->cache(true)->getField('city_id');

    

    a:

    $att3 = substr($att2,$a2);

    $a3 = strpos($att3,'自治县');

    if(!$a3) $a3=strpos($att3,'区');

    if(!$a3) $a3=strpos($att3,'市');

    if(!$a3) $a3=strpos($att3,'县');

    $name = substr($att3,0,$a3-1);

    $awhere['area_name']=array('like',$name.'%') ;

    $awhere['parent_id']=$data['cid'];

    $data['aid'] = M('Area')->where($where['area_name'])->cache(true)->getField('area_id');

    return $data;

}*/

function getAreaId($att,$citynm='',$simcall=''){

    $att=preg_replace('# #','',$att);//var_dump($att);

    if(strstr($att,'北京')){

        $data['pid'] = 110000;

        $data['cid'] = 110100;

        goto a;

    }else if(strstr($att,'上海')){

        $data['pid'] = 310000;

        $data['cid'] = 310100;

        goto a;

    }else if(strstr($att,'天津')){

        $data['pid'] = 120000;

        $data['cid'] = 120100;

        goto a;

    }else if(strstr($att,'重庆')){

        $data['pid'] = 500000;

        $data['cid'] = 500100;

        goto a;

    }else if(strstr($att,'自治区')){

        $a1 = strpos($att,'自治区');

        $i=9;

    }else{

        $a1 = strpos($att,'省');//$i=3;

        // file_put_contents('sareea',$a1);

    }

    $name = mb_substr($att,0,$a1);

    // var_dump($name);

    // var_dump($a1);

    $pwhere['province_name']=array('like',$name.'%') ;

    $data['pid'] = M('Province')->where($pwhere)->getField('province_id');//"province_name like '$name%'"

    // echo M('Province')->_sql();    

    if(empty($i)) $i=3;

    $att2 = mb_substr($att,$a1+$i);//dump($att2);

    if(strstr($att,'神农架')){

        $data['cid'] = 429021;

        $i=15;

        goto a;

    }

    $a2 = strpos($att2,'市');          /// var_dump($att2);

    if(!$a2) {

        $a2=strpos($att2,'自治州');$j=9;

    }

    if(!$a2){

        $a2=strpos($att2,'地区');$j=6;

    } 

    if(!$a2) $a2=strpos($att2,'盟');

    $name = mb_substr($att2,0,$a2);

    $cwhere['city_name']=array('like',$name.'%') ;

    $cwhere['parent_id']=$data['pid'];

    $data['cid'] = M('City')->where($cwhere)->getField('city_id');

    //echo M('City')->_sql();

    // var_dump($name);var_dump($a2);

    a:

    if(empty($j)) $j=3;

    if(empty($a2)){

        if($i ==15){

            $a2=strpos($att,'林区');

        }else{

            $a2=strpos($att,'市'); // echo '<br/>1';var_dump($a2);

            $att2=$att;

            //$att2=mb_substr($att,$a2+3);   echo '<br/>2';var_dump($att2);

        }

    } 



    $att3 = mb_substr($att2,$a2+$j); //echo '<br/>3';var_dump($att3);

    $a3 = strpos($att3,'自治县');

    if(!$a3) $a3=strpos($att3,'农场');

    if(!$a3) $a3=strpos($att3,'旗');

    if(!$a3) $a3=strpos($att3,'区');

    if(!$a3) $a3=strpos($att3,'市');

    if(!$a3) $a3=strpos($att3,'县');

    if(!$a3) $a3=strpos($att3,'镇');

    $name = mb_substr($att3,0,$a3);//echo '<br/>4';

    // var_dump($name);var_dump($a3);

    $awhere['area_name']=array('like',$name.'%') ;

    $awhere['parent_id']=$data['cid'];

    $data['aid'] = M('Area')->where($awhere)->getField('area_id');

    // echo M('Area')->_sql();

    // var_dump($data);

    return $data;

}



/**

 * 判断ip地址格式是否正确

 *  

 * @param string $ip

 * @return bool

 */

function is_ip($ip) {

    return preg_match('/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))$/', $ip);

}



/**

 * 生成淘店通签名

 *  

 * @param $params 参数数组

 * @return string

 */

function tdt_sign($params) {

    ksort($params);

    $paramsStr = '';

    foreach($params as $k => $v) {

        $paramsStr .= $k . $v;

    }

    $paramsStr = C('TDT_SECRET') . $paramsStr . C('TDT_SECRET');

    return strtoupper(md5($paramsStr));

}

function elect_sign($params){

    ksort($params);

    $paramsStr = '';

    foreach($params as $k => $v) {

        $paramsStr .= $k . $v;

    }

    $sercet = '8c363998e026d87fc1ff9eb66d2e3b9f';

    $paramsStr = $sercet . $paramsStr . $sercet;

    return strtoupper(md5($paramsStr));

}

/**

 * 根据$pay_type获取平台

 * @param int $type　支付方式（1：支付宝，2：微信支付）

 *  

 * @return string

 */

function get_pay_type($pay_type){

    switch ($pay_type) {

        case 1:

            $info = '支付宝支付';

            break;

        case 2:

            $info = '微信支付';

            break;

        case 3:

            $info = '货到付款';

            break;

        case 4:

            $info = '网银支付';

            break;

        case 5:

            $info = 'paypal支付';

            break;

        case 6:

            $info = '贝宝支付';

            break;

        case 7:

            $info = '代付';

            break;

        case 8:

            $info = '银联支付';

            break;

        case 9:

            $info = '余额支付';

            break;

        default:

            $info = '';

    }

    return $info;

}

/**

 * 根据$status交易状态

 * @param int $status　交易状态（0:等待买家付款; 1:等待卖家发货,即:买家已付款; 2:等待买家确认收货,即:卖家已发货; 3:买家确认收货,即:交易成功; 4:付款以前，卖家或买家主动关闭交易; 5:付款以后用户退款成功，交易自动关闭）

 * @param int $type 配送方式

 *  

 * @return string

 */

function get_order_status($status,$type = 0,$complain_type=null){

    switch ($status) {

        case 0:

            $info = '等待买家付款';

            break;

        case 1:

            if ($type == 5) {

                $info = '等待门店配送';

            } elseif ($type == 4) {

                $info = '等待卖家确认';

            } else {

                $info = '等待卖家发货';

            }

            break;

        case 2:

            if($type == 4){

                $take_their_name = config('take_their_name')?config('take_their_name'):'自提';

                $info = '等待买家'.$take_their_name;

            }else{

                $info = '等待买家确认收货';

            }

            break;

        case 3:

            $info = '交易完成';

            break;

        case 4:

            $info = '订单关闭';

            break;

        case 5:

            if ($complain_type == 1) {

                $info = '订单关闭(换货成功)';

            } elseif ($complain_type == 2) {

                $info = '订单关闭(退货成功)';

            } else {

                $info = '订单关闭(退\换货成功)';

            }

            break;

        case 6:

            if ($complain_type == 1) {

                $info = '用户换货中';

            } elseif ($complain_type == 2) {

                $info = '用户退货中';

            } else {

                $info = '用户退换货中';

            }

            break;

        default:

            $info = '';

    }

    return $info;

}



/**

 * 打印log

 *  

 */

function log_result($file,$word) {

    $fp = fopen($file, "a");

    flock($fp, LOCK_EX);

    fwrite($fp, "执行日期：" . strftime("%Y-%m-%d-%H：%M：%S", time()) . "\n" . $word . "\n\n");

    flock($fp, LOCK_UN);

    fclose($fp);

}



//检测手机浏览器

function check_agent(){

    $browser = C('browser');

    $browser_id = 0;

    $agent = $_SERVER['HTTP_USER_AGENT'];

    if(!empty($browser)){

        foreach($browser as $key => $rs){

            if(strpos(strtolower($agent),strtolower($rs)) != false){

                $browser_id = $key;

                break;

            }

        }

    }

    return $browser_id;

}



/**

 * 时间过滤器

 * @author Hu Hua Feng

 * @param

 * @return

 * @create 2014-09-11 19:23:45

 */



function smarty_date_format($string, $format = "%Y-%m-%d %H:%M", $default_date = '',$formatter='auto')

{

    /**

     * Include the {@link shared.make_timestamp.php} plugin

     */



    if ($string != '') {

        $timestamp = smarty_make_timestamp($string);

    } elseif ($default_date != '') {

        $timestamp = smarty_make_timestamp($default_date);

    } else {

        return;

    }

    if($formatter=='strftime'||($formatter=='auto'&&strpos($format,'%')!==false)) {

        if (defined('DS') && DS == '\\') {

            $_win_from = array('%D', '%h', '%n', '%r', '%R', '%t', '%T');

            $_win_to = array('%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S');

            if (strpos($format, '%e') !== false) {

                $_win_from[] = '%e';

                $_win_to[] = sprintf('%\' 2d', date('j', $timestamp));

            }

            if (strpos($format, '%l') !== false) {

                $_win_from[] = '%l';

                $_win_to[] = sprintf('%\' 2d', date('h', $timestamp));

            }

            $format = str_replace($_win_from, $_win_to, $format);

        }

        return strftime($format, $timestamp);

    } else {

        return date($format, $timestamp);

    }

}



/**

 * Function: smarty_make_timestamp<br>

 * Purpose:  used by other smarty functions to make a timestamp from a string.

 *

 * @author   Monte Ohrt <monte at ohrt dot com>

 * @param DateTime|int|string $string  date object, timestamp or string that can be converted using strtotime()

 * @return int

 */

function smarty_make_timestamp($string)

{

    if (empty($string)) {

        // use "now":

        return time();

    } elseif ($string instanceof DateTime) {

        return $string->getTimestamp();

    } elseif (strlen($string) == 14 && ctype_digit($string)) {

        // it is mysql timestamp format of YYYYMMDDHHMMSS?

        return mktime(substr($string, 8, 2),substr($string, 10, 2),substr($string, 12, 2),

            substr($string, 4, 2),substr($string, 6, 2),substr($string, 0, 4));

    } elseif (is_numeric($string)) {

        // it is a numeric string, we handle it as timestamp

        return (int) $string;

    } else {

        // strtotime should handle it

        $time = strtotime($string);

        if ($time == -1 || $time === false) {

            // strtotime() was not able to parse $string, use "now":

            return time();

        }

        return $time;

    }

}



/**

 * 更新会员等级

 *  

 * @param int $user_id 买家id

 * @param int $status 升级条件

 * @return bool;

 */

function update_rank($user_id,$status = 0){

    $User = M('User');

    $UserRank = M('UserRank');

    // 获取会员信息

    $info = $User->db(1, 'MASTER_DB')->where('user_id = '.$user_id)->field('shop_id, rank_id, trade_amount, trade_count')->find();

    $rank_id = $info['rank_id'];

    $is_rank_upgrade_status = config('is_rank_upgrade_status', null, $info['shop_id']);

    $is_rank_upgrade_status = is_null($is_rank_upgrade_status)?0:$is_rank_upgrade_status;

    if($status != 3){

        if ($is_rank_upgrade_status != $status) return;

    }

    $user_up_time = M('UserTime')->where('user_id = '.$user_id)->getField('user_up_time');

    if($is_rank_upgrade_status == 0){

        $map = array('user_id'=>$user_id, 'status'=>3);

        if($user_up_time){

            $map['end_time'] = $user_up_time;

        }

        $trade_amount = M('Order')->db(1, 'MASTER_DB')->where($map)->sum('payment');

        $trade_count = M('Order')->db(1, 'MASTER_DB')->where($map)->count(1);

    }else{

        $map = array('user_id'=>$user_id, 'status'=>array('in', '1,2,3'));

        if($user_up_time){

            $map['pay_time'] = $user_up_time;

        }

        $trade_amount = M('Order')->db(1, 'MASTER_DB')->where($map)->sum('payment');

        $trade_count = M('Order')->db(1, 'MASTER_DB')->where($map)->count(1);

    }



    // 卖家id

    $seller_id = M('Shop')->where('shop_id = ' . $info['shop_id'])->getField('seller_id');

    //获取上一个 等级级数 , 和其他数据（等级标准）

    if($rank_id){

        $level = intval($UserRank->where('rank_id='.$rank_id.' AND seller_id = '.$seller_id)->getField('level'));

    }else{

        $level = 0;

    }

    //判断会员等级 并且 提取正确的等级数  $new_rank_id

    $new_rank_id = $rank_id;

    $array = array(

        'seller_id'=>$seller_id,

        'level'=>array('gt',$level)

    );

    $rands = $UserRank->where($array)->field('rank_id, amount, count, level')->order('level desc')->select();

    foreach($rands as $k=>$v){

        if (!empty($v['amount'])){

            if ($trade_amount >= $v['amount']){

                $new_rank_id = $v['rank_id'];

                break;

            }

        }

        if (!empty($v['count'])){

            if ($trade_count >=  $v['count']){

                $new_rank_id = $v['rank_id'];

                break;

            }

        }

    }

    $res = $User->db(0)->where('user_id = '.$user_id)->setField('rank_id', $new_rank_id);

    if($res){

        if(M('UserTime')->where('user_id = '.$user_id)->getField(1)){

            M('UserTime')->where('user_id = '.$user_id)->setField('user_rank_time',NOW_TIME);

        }else{

            $data = array(

                'user_id'=>$user_id,'shop_id'=>$info['shop_id'],'user_rank_time'=>NOW_TIME

            );

            M('UserTime')->add($data);

        }

    }

    return $res;

}



/**

 * 自动审核成功分销商

 *  

 */

function auto_audit($user_id,$shop_id){

    //查询Openid

    $User = M('User');$Agent_apply = M('Agent_apply');$Shop = M('Shop');

    $is_apply = $Agent_apply->where(array('shop_id'=>$shop_id, 'user_id'=>$user_id))->find();

    $is_agent = $User->where('user_id = '.$user_id)->getField('is_agent');

    if($is_agent) return;

    $audit = config('automatic_audit',null,$shop_id);

    if($audit == 1){

        if(!empty($is_apply)){

            $agent_up_time = M('AgentTime')->where('user_id = ' . $user_id)->getField('agent_up_time');

            $audit_amount = config('automatic_audit_amount',null,$shop_id);

            $audit_num =   config('automatic_audit_num',null,$shop_id);

            $audit_map = is_null(config('automatic_audit_map',null,$shop_id))?C('AUTOMATIC_AUDIT_MAP'):config('automatic_audit_map',null,$shop_id);

            $audit_item_id = config('automaic_item_id',null,$shop_id);

            $automatic_item_map = config('automatic_item_map',null,$shop_id);

            $superior_count = config('automatic_level_count',null,$shop_id);

            $automatic_level_count= $User->where('shop_id = ' . $shop_id . ' AND superior_user_id = '.$user_id. ' AND is_user_del = 0')->count(1);

            // 自动审核订单状态

            $audit_order_status = is_null(config('automatic_audit_order_status',null,$shop_id))?C('AUTOMATIC_AUDIT_ORDER_STATUS'):config('automatic_audit_order_status',null,$shop_id);

            $join = '__ORDER_ITEM__ as i on i.order_id = o.order_id';

            if ($audit_order_status == 2) {

                if($audit_item_id){

                    //'user_id = '.$user_id.' and item_id in ('.$audit_item_id.') AND o.status > 0 AND o.status <4'

                    $audit_item_map = array(

                        'user_id'=>$user_id,'item_id'=>array('in',$audit_item_id),

                        'o.status'=>array(array('gt',0),array('lt',4))

                    );

                    if($agent_up_time){

                        $audit_item_map['pay_time']=array('gt',$agent_up_time);

                    }

                    if($automatic_item_map){

                        $automatic_item_count = M('Order')->alias('o')->join($join)->where($audit_item_map)->group('item_id')->select();

                        if(count($automatic_item_count) == count(explode(',',$audit_item_id))){

                            $is_audit_item = true;

                        }else{

                            $is_audit_item = false;

                        }

                    }else{

                        $is_audit_item = M('Order')->alias('o')->join($join)->where($audit_item_map)->getField(1);

                    }

                }

                $map = array('user_id'=>$user_id, 'status'=>array('in', '1,2,3'));

                if($agent_up_time){

                    $map['pay_time']=array('gt',$agent_up_time);

                }

                $uinfo['trade_count'] = M('Order')->where($map)->count(1);

                $uinfo['trade_amount'] = M('Order')->where($map)->sum('payment');

            } else {

                if($audit_item_id){

                    $audit_item_map = array(

                        'user_id'=>$user_id,'item_id'=>array('in',$audit_item_id),

                        'o.status'=>3

                    );

                    if($agent_up_time){

                        $audit_item_map['end_time']=array('gt',$agent_up_time);

                    }

                    if($automatic_item_map){

                        $automatic_item_count = M('Order')->alias('o')->join($join)->where($audit_item_map)->group('item_id')->select();

                        if(count($automatic_item_count) == count(explode(',',$audit_item_id))){

                            $is_audit_item = true;

                        }else{

                            $is_audit_item = false;

                        }

                    }else{

                        $is_audit_item = M('Order')->alias('o')->join($join)->where($audit_item_map)->getField(1);

                    }

                }

                //$uinfo = M('User')->where('user_id = '.$user_id)->field('trade_count,trade_amount')->find();

                $map = array('user_id'=>$user_id, 'status'=>3);

                if($agent_up_time){

                    $map['end_time']=array('gt',$agent_up_time);

                }

                $uinfo['trade_count'] = M('Order')->where($map)->count(1);

                $uinfo['trade_amount'] = M('Order')->where($map)->sum('payment');

            }

            //$access_token = get_weixin_access_token();

            $seller_id = $Shop->where('shop_id = '.$shop_id)->getfield('seller_id');

            $maximum = $Shop->alias('s')->join('left join '.C('DB_PREFIX').'version as v ON s.version_id = v.version_id')->where('s.seller_id = ' . $seller_id)->getField('maximum');

            if($audit_map == 1){

                if($automatic_level_count >= $superior_count && ((($audit_num !== null && $uinfo['trade_count'] >= $audit_num) || ($audit_amount !== null && $uinfo['trade_amount'] >= $audit_amount) || $is_audit_item))){

                    //查询分销商数量

                    $countNum = $User->where('shop_id = '. $shop_id.' AND is_agent = 1')->count(1);

                    if(($countNum < $maximum)){

                        $User->where('user_id = '.$user_id)->save(array('is_agent'=>1, 'agent_type'=>1));

                        $Agent_apply->where(array('shop_id'=>$shop_id,'user_id'=>$user_id))->save(array('status'=>1));

                        //会员成为分销商时间

                        $agent_data = array(

                            'user_id' => $user_id,

                            'agent_time' => NOW_TIME,

                            'dc_shop'=>$shop_id

                        );

                        // 默认到期时间

                        $default_agent_end = intval(config('default_agent_end', null, $shop_id));

                        if ($default_agent_end > 0) {

                            $agent_data['agent_end_time'] = NOW_TIME + $default_agent_end*24*3600;

                        }

                        M('AgentTime')->add($agent_data);



                        //发送微信消息

                        $message = is_null(config('agent_msg_content'))?C('AGENT_MSG_CONTENT'):config('agent_msg_content');

                        $link = C('DOMAIN.CALLBACK_WX')."/User/index/sid/".$shop_id.".html";

                        $message = apply_agent_content($message,$link,$is_apply['agent_name']);

                        D('Mobile/User')->sendMessageAgent($is_apply['openid'],$user_id,$message,1,8);

                        /*if($is_apply['openid']){

                            $message = $is_apply['agent_name'] ." 恭喜，您已成为分销商，现在可以进入会员中心，分销产品啦! ^-^ \n点击进入 ".C('DOMAIN.CALLBACK_WX')."/User/index/sid/".$shop_id.".html";

                            weixin_custom_send($is_apply['openid'], $message, $access_token);

                        }*/

                    }

                }

            }else{

                if($automatic_level_count >= $superior_count && (((($uinfo['trade_count'] >= $audit_num && $audit_num !==null) || ($audit_num ===null && $audit_amount !==null) ) && (($audit_amount !==null && $uinfo['trade_amount'] >= $audit_amount)  || ($audit_amount ===null && $audit_num !==null))) || $is_audit_item)){

                    //查询分销商数量

                    $countNum = $User->where('is_agent = 1 and shop_id = '. $shop_id)->count(1);

                    if(($countNum < $maximum)){

                        $User->where('user_id = '.$user_id)->save(array('is_agent'=>1, 'agent_type'=>1));

                        $Agent_apply->where(array('shop_id'=>$shop_id, 'user_id'=>$user_id))->save(array('status'=>1));

                        //会员成为分销商时间

                        $agent_data = array(

                            'user_id' => $user_id,

                            'agent_time' => NOW_TIME,

                            'dc_shop'=>$shop_id

                        );

                        // 默认到期时间

                        $default_agent_end = intval(config('default_agent_end', null, $shop_id));

                        if ($default_agent_end > 0) {

                            $agent_data['agent_end_time'] = NOW_TIME + $default_agent_end*24*3600;

                        }

                        M('AgentTime')->add($agent_data);

                        //发送微信消息

                        $message = is_null(config('agent_msg_content'))?C('AGENT_MSG_CONTENT'):config('agent_msg_content');

                        $link = C('DOMAIN.CALLBACK_WX')."/User/index/sid/".$shop_id.".html";

                        $message = apply_agent_content($message,$link,$is_apply['agent_name']);

                        D('Mobile/User')->sendMessageAgent($is_apply['openid'],$user_id,$message,1,8);

                        /*if($is_apply['openid']){

                            $message = $is_apply['agent_name'] ." 恭喜，您已成为分销商，现在可以进入会员中心，分销产品啦! ^-^ \n点击进入 ".C('DOMAIN.CALLBACK_WX')."/User/index/sid/".$shop_id.".html";

                            weixin_custom_send($is_apply['openid'], $message, $access_token);

                        }*/

                    }

                }

            }

        }

    }

}



/**

 * 更新分销商等级

 *  

 * @param int $user_id 会员id

 * @return bool;

 */

function update_agent_rank($user_id,$status=0){

    $User = M('User');

    $CommissionLog = D('Home/CommissionLog');

    $AgentRank = M('AgentRank');

    $OrderModel = M('Order');

    $join = '__USER__ as u on u.user_id = o.user_id';

    if(intval($user_id) <=0) return;

    // 判断是否为分销商

    $res = $User->db(1, 'MASTER_DB')->where('user_id = ' . $user_id . ' AND is_user_del = 0')->field('is_agent,shop_id,trade_amount,agent_rank_id,real_openid')->find();

    if ($res['is_agent'] !=1) return;

    $shop_id = $res['shop_id'];

    $real_openid = $res['real_openid'];



    $is_upgrade_status = config('is_upgrade_status', null, $shop_id);

    $is_upgrade_status = is_null($is_upgrade_status)?0:$is_upgrade_status;

    if($status != 3){

        if ($is_upgrade_status != $status) return;

    }

    if($is_upgrade_status == 0){

        $trade_amount = $res['trade_amount'];

        $agent_trade_amount = $OrderModel ->db(1, 'MASTER_DB')->alias('o')->join($join)->where('shop_id = '.$shop_id.' AND o.status = 3 AND (o.superior_user_id='.$user_id.' OR o.top_user_id='.$user_id.' OR o.three_user_id='.$user_id.' OR  o.user_id = '.$user_id.')')->sum('payment');

        //直属下级订单总额

        $junior_order_sum = $OrderModel ->db(1, 'MASTER_DB')->alias('o')->join($join)->where('shop_id = '.$shop_id.' AND o.superior_user_id='.$user_id.' AND o.status = 3')->sum('payment');



    }else{

        $map = array('user_id'=>$user_id, 'status'=>array('in', '1,2,3'));

        $trade_amount = M('Order')->db(1, 'MASTER_DB')->where($map)->sum('payment');

        $agent_trade_amount = $OrderModel ->db(1, 'MASTER_DB')->alias('o')->join($join)->where('shop_id = '.$shop_id.' AND o.status in (1,2,3) AND (o.superior_user_id='.$user_id.' OR o.top_user_id='.$user_id.' OR o.three_user_id='.$user_id.' OR  o.user_id = '.$user_id.')')->sum('payment');

        //直属下级订单总额

        $junior_order_sum = $OrderModel ->db(1, 'MASTER_DB')->alias('o')->join($join)->where('shop_id = '.$shop_id.' AND o.superior_user_id='.$user_id.' AND o.status in (1,2,3)')->sum('payment');

    }

    //下级分销商数量

    $level_user_total = $User->db(1, 'MASTER_DB')->where(' shop_id = '.$shop_id.' AND (superior_user_id = '.$user_id.' OR top_user_id= ' . $user_id .' OR three_user_id= ' . $user_id.') AND is_user_del = 0 AND is_agent = 1')->count(1);

    //直属下级分销商数量

    $level_superior_total = $User->db(1, 'MASTER_DB')->where(' shop_id = '.$shop_id.' AND superior_user_id = '.$user_id.' AND is_user_del = 0 AND is_agent = 1')->count(1);



    //下级会员数目

    $junior_member_num = $User->db(1, 'MASTER_DB')->where(' shop_id = '.$shop_id.' AND (superior_user_id = '.$user_id.' OR top_user_id= ' . $user_id .' OR three_user_id= ' . $user_id.') AND is_user_del = 0')->count(1);



    // 当前分销商佣金比例

    if($res['agent_rank_id']){

        $res = $AgentRank->where('agent_rank_id = ' . $res['agent_rank_id'])->field('superior_ratio,agent_level')->find();

    }

    $now_ratio = $res['superior_ratio'] ? $res['superior_ratio'] : 0;

    $a_level = $res['agent_level']?$res['agent_level']:0;



    // 获取更高佣金的分销商等级

    $map = array('shop_id'=>$shop_id, 'agent_type'=>1, 'agent_level'=>array('gt',$a_level));

    $list = $AgentRank->where($map)->order('agent_level DESC,superior_ratio DESC, agent_rank_id DESC')->select();



    if (!$list) return;

    // 获取会员总佣金

    $total_commission = $CommissionLog->get_total_commission($user_id);



    foreach ($list as $v) {

        $is_match_or = 0; // 或条件是否满足

        $is_match_and = 0; // 与条件是否满足



        // 佣金总收入

        if ($v['upgrade_amount'] !== null) {

            if ($v['is_amount']) {

                if ($total_commission < $v['upgrade_amount']) continue;

                else $is_match_and = 1;

            } elseif (!$is_match_or) {

                if ($total_commission >= $v['upgrade_amount']) $is_match_or = 1;

            }

        }



        // 订单总金额

        if ($v['upgrade_order_amount'] !== null) {

            if ($v['is_order_amount']) {

                if ($trade_amount < $v['upgrade_order_amount']) continue;

                else $is_match_and = 1;

            } elseif (!$is_match_or) {

                if ($trade_amount >= $v['upgrade_order_amount']) $is_match_or = 1;

            }

        }



        // 分销商带来的订单总额

        if ($v['upgrade_agent_amount'] !== null) {

            if ($v['is_agent_amount']) {

                if ($agent_trade_amount < $v['upgrade_agent_amount']) continue;

                else $is_match_and = 1;

            } elseif (!$is_match_or) {

                if ($agent_trade_amount >= $v['upgrade_agent_amount']) $is_match_or = 1;

            }

        }



        // 发展的分销商数

        if ($v['upgrade_agent_num'] !== null) {

            if ($v['is_agent_num']) {

                if ($level_user_total < $v['upgrade_agent_num']) continue;

                else $is_match_and = 1;

            } elseif (!$is_match_or) {

                if ($level_user_total >= $v['upgrade_agent_num']) $is_match_or = 1;

            }

        }



        // 发展的直属下级分销商数

        if ($v['superior_agent_num'] !== null) {

            if ($v['is_superior_num']) {

                if ($level_superior_total < $v['superior_agent_num']) continue;

                else $is_match_and = 1;

            } elseif (!$is_match_or) {

                if ($level_superior_total >= $v['superior_agent_num']) $is_match_or = 1;

            }

        }



        //购买指定商品

        if ($v['automaic_item_id'] !== null) {

            $join1 = '__ORDER_ITEM__ as i on i.order_id = o.order_id';

            $is_audit_item = M('Order')->alias('o')->join($join1)->where('user_id = '.$user_id.' and item_id = '.$v['automaic_item_id'].' AND o.status >0 AND o.status <4')->getField(1);

            if ($v['is_item_id']) {

                if (!$is_audit_item) continue;

                else $is_match_and = 1;

            } elseif (!$is_match_or) {

                if ($is_audit_item) $is_match_or = 1;

            }

        }

        //下级会员数目

        if($v['junior_member_num'] != null) {

            if($v['is_member_num']) {

                if($junior_member_num < $v['junior_member_num'])

                    continue;

                else

                    $is_match_and = 1;

            } elseif(!$is_match_or) {

                if($junior_member_num >= $v['junior_member_num'])

                    $is_match_or = 1;

            }

        }



        //直属下级订单总额

        if($v['junior_order_sum'] != null) {

            if($v['is_order_sum']) {

                if($junior_order_sum < $v['junior_order_sum'])

                    continue;

                else

                    $is_match_and = 1;

            } elseif(!$is_match_or) {

                if($junior_order_sum >= $v['junior_order_sum'])

                    $is_match_or = 1;

            }

        }



        if ($is_match_or || $is_match_and) {

            $agent_rank_id = $v['agent_rank_id'];

            break;

        }

    }



    if (isset($agent_rank_id)){

        $rs = $User->where('user_id = '.$user_id)->setField('agent_rank_id', $agent_rank_id);

        if($rs){

            //升到此等级奖励金额

            if($agent_rank_id != $res['agent_rank_id']){

                $reward_info = $AgentRank->where('agent_rank_id = '.$agent_rank_id.' AND shop_id = '.$shop_id)->field('reward_money,reward_point')->find();

                $reward_money = $reward_info['reward_money'];

                if($reward_money >0){

                    $balance = $User->where('user_id = '.$user_id)->getField('balance');

                    $data = array(

                        'user_id'=>$user_id,

                        'change_num'=>$reward_money,

                        'after_num'=>$balance+$reward_money,

                        'before_num'=>$balance,

                        'type'=>13,

                        'type_id'=>'',

                        'create_time'=>NOW_TIME,

                        'status'=>1,

                        'remark'=>'分销商升级奖励金额',

                        'dc_shop' => $shop_id

                    );

                    $id = M("UserBalance")->add($data);

                    if($id){

                        $User->where('user_id = '.$user_id)->setInc('balance',$reward_money);

                    }

                }

                if($reward_info['reward_point'] > 0){

                    vendor('API_User');

                    $c = new \API_User;

                    $auge = array(

                        'user_id' => $user_id,

                        'points'  => $reward_info['reward_point'],

                        'type'  => 24,

                        'type_id'=>$rs,           //存入等级id

                        'remark' => '分销商升级奖励积分'

                    );

                    $c->sendPoint($auge);

                }

            }



            $update_apply_content = config('update_apply_content',null,$shop_id);

            $update_apply_content = is_null($update_apply_content)?'恭喜您，您在{插入店铺}的分销商等级已升级为{插入分销商等级}！':$update_apply_content;

            $shop_title = M('Shop')->where('shop_id = '.$shop_id)->getField('title');

            $agent_level = M('AgentRank')->where('agent_rank_id = '.$agent_rank_id.' AND shop_id = '.$shop_id)->getField('title');

            $message = update_gent_content($update_apply_content,$shop_title,$agent_level);

            D('Mobile/User')->sendMessageAgent($real_openid,$user_id,$message,1,27,$shop_id);

        }

    }

}



/**

 * 更新分红等级

 *  

 * @param int $user_id 会员id

 * @return bool;

 */

function update_bonus_rank($user_id){

    $User = M('User');$UserBonus = M('UserBonus');

    $CommissionLog = D('Home/CommissionLog');

    $BonusRank = M('BonusRank');

    $OrderModel = M('Order');

    $join = '__USER__ as u on u.user_id = o.user_id';

    // 判断是否为分红会员

    $res = $UserBonus->where('user_id = ' . $user_id)->find();

    if (empty($res)) return;

    $shop_id = $res['shop_id'];

    $user_info = $User->where('user_id = '.$user_id)->field('trade_amount,real_openid')->find();

    $real_openid = $user_info['real_openid'];

    //订单总金额

    $trade_amount = $user_info['trade_amount'];

    //分销商所带来的订单总额

    $agent_trade_amount = $OrderModel ->db(1, 'MASTER_DB')->alias('o')->join($join)->where('shop_id = '.$shop_id.' AND o.status = 3 AND (o.superior_user_id='.$user_id.' OR o.top_user_id='.$user_id.' OR o.three_user_id='.$user_id.' OR  o.user_id = '.$user_id.')')->sum('payment');

    //下级分销商数量

    $level_user_total = $User->where(' shop_id = '.$shop_id.' AND (superior_user_id = '.$user_id.' OR top_user_id= ' . $user_id .' OR three_user_id= ' . $user_id.') AND is_user_del = 0 AND is_agent = 1')->count(1);

    //下级分红人数

    $level_bonus_total = $UserBonus->alias('b')->join('__USER__ as u on u.user_id = b.user_id')->where(' u.shop_id = '.$shop_id.' AND (superior_user_id = '.$user_id.' OR top_user_id= ' . $user_id .' OR three_user_id= ' . $user_id.') AND is_user_del = 0')->count(1);

    // 当前分红比例

    if($res['bonus_rank_id']){

        $res = $BonusRank->where('bonus_rank_id = ' . $res['bonus_rank_id'])->field('bonus_ratio,bonus_level')->find();

    }

    $now_ratio = $res['bonus_ratio'] ? $res['bonus_ratio'] : 0;

    $a_level = $res['bonus_level']?$res['bonus_level']:0;



    // 获取更高佣金的分红等级

    $map = array('shop_id'=>$shop_id, 'bonus_level'=>array('egt',$a_level));

    $list = $BonusRank->where($map)->order('bonus_level DESC,bonus_ratio DESC, bonus_rank_id DESC')->select();



    if (!$list) return;

    // 获取会员总佣金

    $total_commission = $CommissionLog->get_total_commission($user_id);



    foreach ($list as $v) {

        $is_match_or = 0; // 或条件是否满足

        $is_match_and = 0; // 与条件是否满足



        // 佣金总收入

        if ($v['upgrade_amount'] !== null) {

            if ($v['is_amount']) {

                if ($total_commission < $v['upgrade_amount']) continue;

                else $is_match_and = 1;

            } elseif (!$is_match_or) {

                if ($total_commission >= $v['upgrade_amount']) $is_match_or = 1;

            }

        }



        // 订单总金额

        if ($v['upgrade_order_amount'] !== null) {

            if ($v['is_order_amount']) {

                if ($trade_amount < $v['upgrade_order_amount']) continue;

                else $is_match_and = 1;

            } elseif (!$is_match_or) {

                if ($trade_amount >= $v['upgrade_order_amount']) $is_match_or = 1;

            }

        }



        // 分销商带来的订单总额

        if ($v['upgrade_agent_amount'] !== null) {

            if ($v['is_agent_amount']) {

                if ($agent_trade_amount < $v['upgrade_agent_amount']) continue;

                else $is_match_and = 1;

            } elseif (!$is_match_or) {

                if ($agent_trade_amount >= $v['upgrade_agent_amount']) $is_match_or = 1;

            }

        }



        // 发展的分销商数

        if ($v['upgrade_agent_num'] !== null) {

            if ($v['is_agent_num']) {

                if ($level_user_total < $v['upgrade_agent_num']) continue;

                else $is_match_and = 1;

            } elseif (!$is_match_or) {

                if ($level_user_total >= $v['upgrade_agent_num']) $is_match_or = 1;

            }

        }

        // 分红下级人数

        if ($v['bonus_level_num'] !== null) {

            if ($v['is_level_num']) {

                if ($level_bonus_total < $v['bonus_level_num']) continue;

                else $is_match_and = 1;

            } elseif (!$is_match_or) {

                if ($level_bonus_total >= $v['bonus_level_num']) $is_match_or = 1;

            }

        }

        if ($is_match_or || $is_match_and) {

            $bonus_rank_id = $v['bonus_rank_id'];

            break;

        }

        /* if ($v['upgrade_amount'] !== null && $total_commission >= $v['upgrade_amount']) {

             $bonus_rank_id = $v['bonus_rank_id'];

             break;

         } elseif ($v['upgrade_order_amount'] !== null && $trade_amount >= $v['upgrade_order_amount']) {

             $bonus_rank_id = $v['bonus_rank_id'];

             break;

         }elseif ($v['upgrade_agent_amount'] !== null && $agent_trade_amount >= $v['upgrade_agent_amount']) {

             $bonus_rank_id = $v['bonus_rank_id'];

             break;

         }elseif ($v['upgrade_agent_num'] !== null && $level_user_total >= $v['upgrade_agent_num']) {

             $bonus_rank_id = $v['bonus_rank_id'];

             break;

         }*/

    }

    if (isset($bonus_rank_id)){

        $rs = $UserBonus->where('user_id = '.$user_id)->setField('bonus_rank_id', $bonus_rank_id);

        if($rs){

            $bonus_msg_content = config('bonus_msg_content',null,$shop_id);

            $bonus_msg_content = is_null($bonus_msg_content)?'恭喜您，您在{插入店铺}的分红等级已升级为{插入分红等级}！':$bonus_msg_content;

            $shop_title = M('Shop')->where('shop_id = '.$shop_id)->getField('title');

            $bonus_level = $BonusRank->where('bonus_rank_id = '.$bonus_rank_id.' AND shop_id = '.$shop_id)->getField('title');

            $message = update_gent_content($bonus_msg_content,$shop_title,null,$bonus_level);

            D('Mobile/User')->sendMessageAgent($real_openid,$user_id,$message,1,44,$shop_id);

        }

    }

}



/*

 * 获取当前用户的所有权限

 */

function get_all_my_priv($priv_str) {

    $priv_str_arr = explode(',', $priv_str);

    require (APP_PATH.'Common/Conf/priv.php');



    if(!$priv_str){

        return array();

    }



    $my_menu_file = array();

    $i = 0;

    foreach ($admin_menu_file as $k => $v) { //$v = array('id' => 'XX', 'name' => 'XX', 'mod_do_url' => '', 'in_menu' => '', 0=>array(),1=>Array()...);

        if (!is_array($v)) {

            continue;

        }

        if (in_array($v['id'], $priv_str_arr)) {

            $my_menu_file[$i] = array('id' => $v['id'], 'name' => $v['name'], 'mod_do_url' => $v['mod_do_url'], 'in_menu' => $v['in_menu']);

        } else {

            continue;

        }



        $p = 0;

        foreach ($v as $m => $n) { //有效的（即是数组的值）项$n = array('id' => 'XX', 'name' => 'XX', 'mod_do_url' => '/XX-acp_XX', 'in_menu' => '');

            if (!is_array($n)) {

                continue;

            }

            if ( isset($n['id']) && in_array($n['id'], $priv_str_arr)) {

                $my_menu_file[$i][$p] = array('id' => $n['id'], 'name' => $n['name'], 'mod_do_url' => $n['mod_do_url'], 'in_menu' => $n['in_menu']);

                $p++;

            }

        }



        $i++;

    }



    return $my_menu_file;

}



/*

 * 验证权限

 */

function checkpriv($my_menu_file, $priv_str, $mod_do_url, $nz_curpage = false) {



    $priv_str_arr = explode(',', $priv_str);



    $have_priv = false;

    $have_find = false;



    foreach ($my_menu_file as $k => $v) {

        if (is_array($v)) {

            foreach ($v as $m => $n) {

                if (is_array($n) && strtolower($n['mod_do_url']) == strtolower($mod_do_url)) {

                    if (in_array($n['id'], $priv_str_arr)) {

                        $have_priv = true;

                    }



                    $have_find = true;

                    break;

                }

            }

        }

        if ($have_find) {

            break;

        }

    }

    return $have_priv;

}





/**

 * 把返回的数据集转换成Tree

 *  

 * @param array $list 要转换的数据集

 * @param string $pk 主键字段

 * @param string $pid parent标记字段

 * @param string $child child索引

 * @param int $root 根id

 * @return array

 */

function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {

    // 创建Tree

    $tree = array();

    if(is_array($list)) {

        // 创建基于主键的数组引用

        $refer = array();

        foreach ($list as $key => $data) {

            $refer[$data[$pk]] =& $list[$key];

        }



        foreach ($list as $key => $data) {

            // 判断是否存在parent

            $parentId =  $data[$pid];

            if ($root == $parentId) {

                $tree[] =& $list[$key];



            }else{

                if (isset($refer[$parentId])) {

                    $parent =& $refer[$parentId];

                    $parent[$child][] =& $list[$key];

                }

            }

        }

    }

    return $tree;



}



/**

 * 去除父级分类的url

 * @author gxz

 * @param array &$list 数据集的引用

 * @return void

 */

function list_of_url(&$list, $row1 = 'child', $row2 = 'link') {

    if(is_array($list)) {

        foreach ($list as &$v) {

           if(isset($v[$row1])){

             $v[$row2] = '';

             list_of_url($v[$row1]);

           }

        }

    }

}



/**

 * 去除图片的后缀

 * @param $img_path 图片路径

 *  

 */

function delImgsuffix($img_path){

    if($pop = strrpos($img_path,'@!')){

        $img_path = substr($img_path,0,$pop);

    }

    return $img_path;

}



/**

 * 字符串截取，支持中文和其他编码

 * @static

 * @access public

 * @param string $str 需要转换的字符串

 * @param string $start 开始位置

 * @param string $length 截取长度

 * @param string $charset 编码格式

 * @param string $suffix 截断显示字符

 * @return string

 */

function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {

    if(function_exists("mb_substr"))

        $slice = mb_substr($str, $start, $length, $charset);

    elseif(function_exists('iconv_substr')) {

        $slice = iconv_substr($str,$start,$length,$charset);

        if(false === $slice) {

            $slice = '';

        }

    }else{

        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";

        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";

        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";

        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";

        preg_match_all($re[$charset], $str, $match);

        $slice = join("",array_slice($match[0], $start, $length));

    }

    if(mb_strlen($slice,'utf-8')>15 && $suffix){

        $slice = $slice.'...';

    }

    return $slice;

}



//获取淘宝类目信息

function getItempropsGetRequest($Cid, $field='cid,pid,parent_pid,is_key_prop,is_sale_prop,is_color_prop,is_enum_prop,is_input_prop,is_item_prop,child_path,type,attr_keys,parent_vid,name,is_key_prop,must,multi,prop_values,status,sort_order,child_template,is_allow_alias,features'){



    $api_getway  = 'http://uapi.tmallshop.cn/api?';

    $order_params = array(

        'sign_method' => 'md5',

        'v' => '2.0',

        'method' => 'taobao.itemprops.get',

        'timestamp' => time(),

        'format' => 'json',

        'app_key' => C('TDT_KEY'),

        'fields' => $field,

        'cid' => $Cid,

    );

    $sign = tdt_sign($order_params);

    $order_params['sign'] = $sign;

    $res = curl($api_getway, $order_params);

    $res = json_decode($res);

    $res = object_to_array($res->itemprops_get_response);

    foreach($res['item_props']['item_prop']  as $key=>$val){

        if(!$val['is_sale_prop']){

            unset($res['item_props']['item_prop'][$key]);

        }

    }

    $res = json_encode($res);

    return $res;

}



/*

 * 根据$status获取快递公司名字

 * @param int $type　快递公司（1 => '顺丰', 2 => '申通', 3 => '圆通', 4 => 'EMS', 5 => '中通', 6 => '韵达', 7 => '中国邮政', 8 => '宅急送', 9 => '天天'）

 *  

 * @return string

 */

function get_express($status){

    $express = C('EXPRESS');

    if ($status == 10) return '';

    return $express[$status];

}



/**

 * 获取微信访问令牌

 *  

 * @return string

 */

function get_weixin_access_token($seller_id=SID, $type=1) {

    $map = array('seller_id'=>$seller_id, 'type'=>$type);

    $wx_info = M('PubWeixin')->db(1, 'MASTER_DB')->where($map)->field('app_id, app_secret, access_token, access_token_due_time')->find();

    if (!$wx_info['app_id']) return false;

    if ($wx_info['access_token'] && ($wx_info['access_token_due_time'] > NOW_TIME)) return $wx_info['access_token'];



    $AppId = $wx_info['app_id'];

    $AppSecret = $wx_info['app_secret'];



    if ($AppSecret) {

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $AppId . "&secret=" . $AppSecret;

        $info = json_decode(curl($url), true);

        if ($info['access_token']) {

            $data = array('access_token' => $info['access_token'], 'access_token_due_time' => NOW_TIME + $info['expires_in'] - 600);

            M('PubWeixin')->where($map)->save($data);

        }

        $access_token = $info['access_token'];

    } else {

        // 是否已接入微信开放平台

        $is_open_wx = M('AcpConfig')->where(array('config_name'=>'is_open_wx'))->getField('config_value');

        if ($is_open_wx) {

            $shop_id = M('Shop')->where('seller_id = ' . $seller_id)->getField('shop_id');

            $c = new \Common\Controller\Open();

            $access_token = $c->api_authorizer_token($shop_id, $type);

        }

    }



    return $access_token;

}



/**

 * 获取微信的用户信息

 *  

 */

function get_weixin_user_info($openid,$access_token){

    $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";

    $userInfo =  json_decode(curl($url), true);

    return $userInfo;

}



/**

 * 微信发送客服消息

 *  

 * $param int $type 消息类型（1：文本消息，2：图文消息，3：图片）

 */

function weixin_custom_send($open_id, $message, $access_token, $type = 1) {

    $apiUrl = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;



    if ($type == 2) {

        $data = array(

            'touser' => $open_id,

            'msgtype' => 'news',

            'news' => array(

                'articles' => $message

            ),

        );

    } elseif ($type == 3) {

        $data = array(

            'touser' => $open_id,

            'msgtype' => 'image',

            'image' => array(

                'media_id' => $message

            ),

        );

    } else {

        $message = str_replace('<div>', '', $message);

        $message = str_replace('</div>', '', $message);

        $data = array(

            'touser' => $open_id,

            'msgtype' => 'text',

            'text' => array(

                'content' => $message

            ),

        );

    }



    $result = \Org\Util\Util::curlPost($apiUrl, \Org\Util\JSON::arrayToJson($data));



    $res = json_decode($result, true);

    if ($res['errcode']) {

//        error_log("\n" . json_encode($data) . "\n" . $result, 3, './Upload/log/weixin_custom_send.log');

        if (($res['errcode'] == 40001) && defined('SID')) {

            $map = array('seller_id'=>SID, 'type'=>1);

            M('PubWeixin')->where($map)->setField('access_token', '');

        }

    }



    return $result;

}





/**

 * 计算订单佣金

 * @author xuwangbing

 */

function create_order_commission($order_id){

    $Order = D('Order');

    $User = D('User');

    $UserDls = M('UserDls');

    $order_info = $Order->db(1, 'MASTER_DB')

        ->where('order_id='.$order_id)

        -> field('create_time,point_fee,fund_fee,dc_shop,user_id,order_id,payment,post_fee,address_id,is_self_take,self_address_id,coupon_repurchase_price,is_general')

        ->find();



    // 订单不存在!

    if(!$order_info) return false;



    // 积分抵现的订单是否参与返佣

    $is_point_cash_commission = config('is_point_cash_commission');

    if ($is_point_cash_commission === '0' && $order_info['point_fee']) return true;

    

    // 金币抵现的订单是否参与返佣

    $is_fund_cash_commission = config('is_fund_cash_commission');

    if ($is_fund_cash_commission === '0' && $order_info['fund_fee']) return true;

    // file_put_contents('jbi',$is_fund_cash_commission);

    $shopId = intval($order_info['dc_shop']);

    //是否分销模式紧缩

    $is_fenxiao_tighten = config('is_fenxiao_tighten');

    // file_put_contents('is_fenxiao_tighten',$is_fenxiao_tighten );

    $user_info = $User->where('user_id='.$order_info['user_id'])->field('superior_user_id,top_user_id,three_user_id,is_agent,province_id,city_id,area_id,town_id')->find();

    if(!$user_info) return false;

    if($is_fenxiao_tighten){

        $user_info['superior_user_id'] = get_fx_pid( $order_info['user_id'] );

        if(empty($user_info['superior_user_id'])){

            $user_info['superior_user_id'] = 0;

            $user_info['top_user_id'] = 0;

            $user_info['three_user_id'] = 0;

        }else{

            $user_info['top_user_id'] = get_fx_pid($user_info['superior_user_id']);

            if(!$user_info['top_user_id']){

                $user_info['top_user_id'] = 0;

                $user_info['three_user_id'] = 0;

            }else{

                $user_info['three_user_id'] = get_fx_pid($user_info['top_user_id'] );

            }

             // file_put_contents('1',json_encode($user_info));

        }

        

    }else{

        $user_info = $User->where('user_id='.$order_info['user_id'])

        ->field('superior_user_id,top_user_id,three_user_id,is_agent')

        ->find();

        if(!$user_info) return false;

    }

    // file_put_contents('fx',json_encode($user_info));

    $map = array(

        'shop_id'       => $shopId,

        'config_name'   => array('in', array('directly_online_ratio', 'superior_online_ratio', 'three_online_ratio'))

    );

    $config = D('Config') -> where($map)-> select();

    $default_ratio = array();



    // 是否开启分销内购

    $is_fenxiao_ins = config('is_fenxiao_ins', null, $shopId);

    if ($is_fenxiao_ins && $user_info['is_agent']) {

        // 成为分销商之前不能有佣金

        $mAgentTime = M('AgentTime');

        $agentTimeWhere = array(

            'user_id' => $order_info['user_id']

        );

        $agentUserInfo = $mAgentTime->where($agentTimeWhere)->find();

        if(!$agentUserInfo || ($agentUserInfo['agent_time'] <= $order_info['create_time'])) {

            $user_info['three_user_id'] = $user_info['top_user_id'];

            $user_info['top_user_id'] = $user_info['superior_user_id'];

            $user_info['superior_user_id'] = $order_info['user_id'];

        }

    }

    // 代理商信息

    $dls_info = $UserDls->where('user_id = ' . $order_info['user_id'])->find();



    // 是否为区域代理

    $dls_mode = config('dls_mode', null, $shopId);

    if ($dls_mode == 1 || $dls_mode == 2) {

        if ($order_info['is_self_take'] && $order_info['self_address_id']) {

            $address_info = M('SelfAddress')

                ->where(array('self_address_id' => $order_info['self_address_id']))

                ->field('province_id, city_id, area_id')

                ->find();

        }else{

            $address_info = M('UserAddress')

                ->where(array('address_id' => $order_info['address_id']))

                ->field('province_id, city_id, area_id')

                ->find();

        }

        if ($address_info['province_id']) {

            // 省代

            $map = array(

                'shop_id'   => $shopId,

                'is_dls'    => 1,

                'dls_type'  => 1,

                'rank'      => 1,

                'region'    => array('like', '%'.$address_info['province_id'].'%')

            );

            $p_dls = $UserDls->where($map)->getField('user_id');

            if ($p_dls) $dls_info['superior_dls_id'] = $p_dls;

            elseif ($dls_mode == 2) $dls_info['superior_dls_id'] = null;

        }

        if ($address_info['city_id']) {

            // 市代

            $map = array(

                'shop_id'   => $shopId,

                'is_dls'    => 1,

                'dls_type'  => 1,

                'rank'      => 2,

                'region'    => array('like', '%'.$address_info['city_id'].'%')

            );

            $c_dls = $UserDls->where($map)->getField('user_id');

            if ($c_dls) $dls_info['top_dls_id'] = $c_dls;

            elseif ($dls_mode == 2) $dls_info['top_dls_id'] = null;

        }

        if ($address_info['area_id']) {

            // 区代

            $map = array(

                'shop_id'   => $shopId,

                'is_dls'    => 1,

                'dls_type'  => 1,

                'rank'      => 3,

                'region'    => array('like', '%'.$address_info['area_id'].'%')

            );

            $a_dls = $UserDls->where($map)->getField('user_id');

            if ($a_dls) $dls_info['three_dls_id'] = $a_dls;

            elseif ($dls_mode == 2) $dls_info['three_dls_id'] = null;

        }

    }

    //是否为身份证锁定代理

    if ($dls_mode == 3) {

        if ($user_info['province_id']) {

            // 省代

            $map = array(

                'shop_id'   => $shopId,

                'is_dls'    => 1,

                'dls_type'  => 1,

                'rank'      => 1,

                'region'    => array('like', '%'.$user_info['province_id'].'%')

            );

            $p_dls = $UserDls->where($map)->getField('user_id');

            if ($p_dls) $dls_info['superior_dls_id'] = $p_dls;

            else $dls_info['superior_dls_id'] = null;

        }

        if ($user_info['city_id']) {

            // 市代

            $map = array(

                'shop_id'   => $shopId,

                'is_dls'    => 1,

                'dls_type'  => 1,

                'rank'      => 2,

                'region'    => array('like', '%'.$user_info['city_id'].'%')

            );

            $c_dls = $UserDls->where($map)->getField('user_id');

            if ($c_dls) $dls_info['top_dls_id'] = $c_dls;

            else $dls_info['top_dls_id'] = null;

        }

        if ($user_info['area_id']) {

            // 区代

            $map = array(

                'shop_id'   => $shopId,

                'is_dls'    => 1,

                'dls_type'  => 1,

                'rank'      => 3,

                'region'    => array('like', '%'.$user_info['area_id'].'%')

            );

            $a_dls = $UserDls->where($map)->getField('user_id');

            if ($a_dls) $dls_info['three_dls_id'] = $a_dls;

            else $dls_info['three_dls_id'] = null;

        }

        if ($user_info['town_id']) {

            // 乡镇区代

            $map = array(

                'shop_id'   => $shopId,

                'is_dls'    => 1,

                'dls_type'  => 1,

                'rank'      => 4,

                'region'    => array('like', '%'.$user_info['town_id'].'%')

            );

            $a_dls = $UserDls->where($map)->getField('user_id');

            if ($a_dls) $dls_info['four_dls_id'] = $a_dls;

            else $dls_info['four_dls_id'] = null;

        }

    }



    $is_dls_fenxiao = config('is_dls_fenxiao', null, $shopId); // 代理商是否拿全民分销佣金

    

    if ($dls_info['four_dls_id']) {

        if (!$is_dls_fenxiao) {

            if ($dls_info['four_dls_id'] == $user_info['superior_user_id']) {

                $user_info['superior_user_id'] = null;

            } elseif ($dls_info['four_dls_id'] == $user_info['top_user_id']) {

                $user_info['top_user_id'] = null;

            } elseif ($dls_info['four_dls_id'] == $user_info['three_user_id']) {

                $user_info['three_user_id'] = null;

            }

        }



        $four_dls_ratio = $UserDls

            ->where(array('user_id'=>$dls_info['four_dls_id'], 'is_dls'=>1, 'rank'=>4))

            ->getField('ratio');

    }

    if ($dls_info['three_dls_id']) {

        if (!$is_dls_fenxiao) {

            if ($dls_info['three_dls_id'] == $user_info['superior_user_id']) {

                $user_info['superior_user_id'] = null;

            } elseif ($dls_info['three_dls_id'] == $user_info['top_user_id']) {

                $user_info['top_user_id'] = null;

            } elseif ($dls_info['three_dls_id'] == $user_info['three_user_id']) {

                $user_info['three_user_id'] = null;

            }

        }



        $three_dls_ratio = $UserDls

            ->where(array('user_id'=>$dls_info['three_dls_id'], 'is_dls'=>1, 'rank'=>3))

            ->getField('ratio');

        if ($four_dls_ratio) {

            $three_dls_ratio -= $four_dls_ratio;

            if ($three_dls_ratio < 0) $three_dls_ratio = 0;

        }

    }

    if ($dls_info['top_dls_id']) {

        if (!$is_dls_fenxiao) {

            if ($dls_info['top_dls_id'] == $user_info['superior_user_id']) {

                $user_info['superior_user_id'] = null;

            } elseif ($dls_info['top_dls_id'] == $user_info['top_user_id']) {

                $user_info['top_user_id'] = null;

            } elseif ($dls_info['top_dls_id'] == $user_info['three_user_id']) {

                $user_info['three_user_id'] = null;

            }

        }



        $top_dls_ratio = $UserDls->where(array('user_id'=>$dls_info['top_dls_id'], 'is_dls'=>1, 'rank'=>2))

            ->getField('ratio');

        if ($three_dls_ratio) {

            $top_dls_ratio -= ($three_dls_ratio+$four_dls_ratio);

            if ($top_dls_ratio < 0) $top_dls_ratio = 0;

        }

    }

    if ($dls_info['superior_dls_id']) {

        if (!$is_dls_fenxiao) {

            if ($dls_info['superior_dls_id'] == $user_info['superior_user_id']) {

                $user_info['superior_user_id'] = null;

            } elseif ($dls_info['superior_dls_id'] == $user_info['top_user_id']) {

                $user_info['top_user_id'] = null;

            } elseif ($dls_info['superior_dls_id'] == $user_info['three_user_id']) {

                $user_info['three_user_id'] = null;

            }

        }



        $superior_dls_ratio = $UserDls

            ->where(array('user_id'=>$dls_info['superior_dls_id'], 'is_dls'=>1, 'rank'=>1))

            ->getField('ratio');

        if (($top_dls_ratio + $three_dls_ratio) > 0) {

            $superior_dls_ratio -= ($top_dls_ratio + $three_dls_ratio+$four_dls_ratio);

            if ($superior_dls_ratio < 0) $superior_dls_ratio = 0;

        }

    }



    $order_item = D('OrderItem')

        ->db(1, 'MASTER_DB')

        ->alias('o')

        ->join('__ITEM__ i ON o.item_id = i.item_id')

        ->join('tp_order ord ON o.order_id = ord.order_id')

        ->where('o.order_id='.$order_info['order_id'])

        ->field('ord.user_id,o.order_id,o.order_item_id,o.sku_id,o.current_price, o.num, i.directly_money, i.superior_money, i.three_money, i.directly_rate, i.superior_rate, i.three_rate,item_limit_discount_id,item_miao_id, i.is_fx_commission, i.is_dl_commission, i.is_store_commission, i.is_staff_commission,i.item_id,i.fullback_id,i.gift_bag,i.consume_up,i.recommend_bouns')

        ->select();
       
    //礼包标记
    $OrderItemGi = D('OrderItem');

    if($order_info['is_general']==0 && empty($order_info['funds'])){


        foreach ($order_item as  $val) {

            if($val['gift_bag'] == 1){
            
                $OrderItemGi->where(array('order_item_id'=>$val['order_item_id']))->data(array('is_gift_bag'=>1))->save();    
            }
            if($val['consume_up'] == 1){
             
                $OrderItemGi->where(array('order_item_id'=>$val['order_item_id']))->data(array('consume_up'=>1))->save(); 
            }

            if($val['recommend_bouns'] == 1){
             
                $OrderItemGi->where(array('order_item_id'=>$val['order_item_id']))->data(array('recommend_bouns'=>1))->save(); 
            }

            
        }
    }


    foreach($config as $rs){

        $default_ratio[$rs['config_name']] = $rs['config_value'];

    }

    //全返订单生成
    if($order_info['is_general']==0 && empty($order_info['point_fee']) && empty($order_info['fund_fee'])){
        $order_fullback = array();
        $Fullback = M('fullback');
        foreach ($order_item as $key => $val){
            if($val['fullback_id']>0){
                if(empty($order_fullback[$val['fullback_id']]['item_price'])){
                    $order_fullback[$val['fullback_id']]['item_price'] = 0;
                    $order_fullback[$val['fullback_id']]['item_id'] = '';    
                }
                $order_fullback[$val['fullback_id']]['item_price'] += $val['current_price']*$val['num'];
                $order_fullback[$val['fullback_id']]['item_id'] .= $val['item_id'].',';
            }
        }
        $fullback_data = array('shop_id'=>SHOP_ID,'fullback_id'=>0,'user_id'=>UID,'order_id'=>$order_id,'status'=>0);
        foreach ($order_fullback as $key => $val) {
            $fullback_info = $Fullback->where(array('fullback_id'=>$key))->find();
            if(empty($fullback_info)) continue;
            $fullback_data['fullback_id'] = $key;
            $fullback_data['item_price'] = $val['item_price'];
            $fullback_data['priceevery'] = $val['item_price']*$fullback_info['permillage']/1000;
            $fullback_data['price'] = round($fullback_data['priceevery'],2)*$fullback_info['allday'];
            $fullback_data['day'] = $fullback_info['allday'];
            $fullback_data['permillage'] = $fullback_info['permillage'];
            $fullback_data['item_id'] = substr($val['item_id'],0,strlen($val['item_id'])-1);
            // dump($fullback_data);exit;
            M('fullback_order')->data($fullback_data)->add();
        }
    }

    $ratio = ratio_commission($user_info,$default_ratio);

    // 判断上线是否为分销商

    $is_superior_agent = $superior_agent_rank = 0;

    if($user_info['superior_user_id'] > 0){

        if ($res = $User->where('user_id = ' . $user_info['superior_user_id'] . ' AND is_user_del = 0 AND shop_id = ' . $shopId)

            ->field('is_agent, agent_rank_id')->find()) {

            if ($res['is_agent'] == 1 || $res['is_agent'] == 3) {

                $is_superior_agent = 1;

                $superior_agent_rank = $res['agent_rank_id'];

            }

        }

    }



    $is_top_agent = $top_agent_rank = 0;

    if($user_info['top_user_id'] > 0){

        if ($res = $User->where('user_id = ' . $user_info['top_user_id'] . ' AND is_user_del = 0 AND shop_id = ' . $shopId)->field('is_agent, agent_rank_id')->find()) {

            if ($res['is_agent'] == 1 || $res['is_agent'] == 3) {

                $is_top_agent = 1;

                $top_agent_rank = $res['agent_rank_id'];

            }

        }

    }



    $is_three_agent = $three_agent_rank = 0;

    if($user_info['three_user_id'] > 0){

        if ($res = $User->where('user_id = ' . $user_info['three_user_id'] . ' AND is_user_del = 0 AND shop_id = ' . $shopId)

            ->field('is_agent, agent_rank_id')->find()) {

            if ($res['is_agent'] == 1 || $res['is_agent'] == 3) {

                $is_three_agent = 1;

                $three_agent_rank = $res['agent_rank_id'];

            }

        }

    }

    // 是否在申请退款

    $complain_order_id = M('ComplainOrder')

        ->where('order_id = ' . $order_id.' AND status !=2')

        ->getField('complain_order_id');



    // 是否使用实付款计算分销商佣金

    $is_order_money = 1;

    foreach ($order_item as &$va) {

        if($order_info['coupon_repurchase_price']){

                $repurchase_info = M('ItemRepurchase')->where('item_id = '.$va['item_id'].' AND shop_id = '.$shopId)->find();

            if(!empty($repurchase_info)) {

                $va = array_merge($va, $repurchase_info);

                $va['current_price'] = $repurchase_info['repurchase_price'];

            }

        }

        if ($va['is_fx_commission']) {

            if ($superior_agent_rank) $superior_agent_info = M('ItemAgentRank')->where(array('item_id'=>$va['item_id'], 'agent_rank_id'=>$superior_agent_rank))->find();

            if ($top_agent_rank) $top_agent_info = M('ItemAgentRank')->where(array('item_id'=>$va['item_id'], 'agent_rank_id'=>$top_agent_rank))->find();

            if ($three_agent_rank) $three_agent_info = M('ItemAgentRank')->where(array('item_id'=>$va['item_id'], 'agent_rank_id'=>$three_agent_rank))->find();



            if (!empty($superior_agent_info['directly_money'])) $va['directly_agent_money'] = $superior_agent_info['directly_money'];

            if (!empty($superior_agent_info['directly_rate'])) $va['directly_agent_rate'] = $superior_agent_info['directly_rate'];

            if (!empty($top_agent_info['superior_money'])) $va['superior_agent_money'] = $top_agent_info['superior_money'];

            if (!empty($top_agent_info['superior_rate'])) $va['superior_agent_rate'] = $top_agent_info['superior_rate'];

            if (!empty($three_agent_info['three_money'])) $va['three_agent_money'] = $three_agent_info['three_money'];

            if (!empty($three_agent_info['three_rate'])) $va['three_agent_rate'] = $three_agent_info['three_rate'];



            if (($va['directly_money'] > 0)

                || ($va['superior_money'] > 0)

                || ($va['three_money'] > 0)

                || ($va['directly_rate'] > 0)

                || ($va['superior_rate'] > 0)

                || ($va['three_rate'] > 0)) {

                $is_order_money = 0;

                continue;

            }



            if (!empty($superior_agent_info['directly_money']) || !empty($superior_agent_info['directly_rate'])

                || !empty($top_agent_info['superior_money']) || !empty($top_agent_info['superior_rate'])

                || !empty($three_agent_info['three_money']) || !empty($three_agent_info['three_rate'])

            ) {

                $is_order_money = 0;

                continue;

            }

        }

    }

    if ($complain_order_id) $is_order_money = 0;

    // 是否使用实付款计算代理商佣金

    $is_dls_money = 1;

    if ($complain_order_id) {

        $is_dls_money = 0;

    } else {

        foreach ($order_item as $v) {

            if($order_info['coupon_repurchase_price']){

                $repurchase_info = M('ItemRepurchase')->where('item_id = '.$v['item_id'].' AND shop_id = '.$shopId)->find();

            }

            if(!empty($repurchase_info)){

                $dls_commission = $repurchase_info;

            }else{

                $dls_commission = M('ItemDls')

                    ->where('item_id = ' . $v['item_id'])

                    ->find();

            }

            if ($v['is_dl_commission'] && (($dls_commission['dls_directly_money'] > 0)

                    || ($dls_commission['dls_superior_money'] > 0)

                    || ($dls_commission['dls_three_money'] > 0)

                    || ($dls_commission['dls_four_money'] > 0)

                    || ($dls_commission['dls_directly_rate'] > 0)

                    || ($dls_commission['dls_superior_rate'] > 0)

                    || ($dls_commission['dls_three_rate'] > 0)

                    || ($dls_commission['dls_four_rate'] > 0))) {

                $is_dls_money = 0;

                break;

            }

        }

    }



    // 是否使用实付款计算门店佣金

    $is_store_money = 1;

    if ($complain_order_id) {

        $is_store_money = 0;

    } else {

        foreach ($order_item as $v) {

            if($order_info['coupon_repurchase_price']){

                 $repurchase_info = M('ItemRepurchase')->where('item_id = '.$v['item_id'].' AND shop_id = '.$shopId)->find();

            }

            if(!empty($repurchase_info)){

                $dls_commission = $repurchase_info;

            }else{

                $dls_commission = M('ItemDls')

                    ->where('item_id = ' . $v['item_id'])

                    ->find();

            }

            if ($v['is_store_commission'] && (($dls_commission['store_money'] > 0)

                    || ($dls_commission['store_rate'] > 0))) {

                $is_store_money = 0;

                break;

            }

        }

    }



    // 是否使用实付款计算员工佣金

    $is_staff_money = 1;

    if ($complain_order_id) {

        $is_staff_money = 0;

    } else {

        foreach ($order_item as $v) {

            if($order_info['coupon_repurchase_price']){

                $repurchase_info = M('ItemRepurchase')->where('item_id = '.$v['item_id'].' AND shop_id = '.$shopId)->find();

            }

            if(!empty($repurchase_info)){

                $dls_commission = $repurchase_info;

            }else{

                $dls_commission = M('ItemDls')

                    ->where('item_id = ' . $v['item_id'])

                    ->find();

            }

            if ($v['is_staff_commission'] && (($dls_commission['staff_money'] > 0)

                    || ($dls_commission['staff_rate'] > 0))) {

                $is_staff_money = 0;

                break;

            }

        }

    }



    // 运费是否参与返佣

    $is_post_fee_commission = config('is_post_fee_commission', null, $shopId);



    //计算直属上线佣金

    $superior_order_commission = 0;



    //计算上级上线佣金

    $to_order_commission = 0;



    //计算三级上线佣金

    $three_order_commission = 0;





    // 买家所属门店,员工

    $store_ratio = $staff_ratio = $store_id = $staff_id = 0;

    $store_info = M('UserStore')->where('user_id = ' . $order_info['user_id'])->find();

    if ($store_info) {

        // $store_id = $store_info['store_id'];

        // if ($store_id) {

        //     $agent_rank_id = M('User')->where(array('user_id'=>$store_id, 'is_agent'=>3))->getField('agent_rank_id');

        //     if ($agent_rank_id) {

        //         $store_ratio = M('AgentRank')->where(array('agent_rank_id'=>$agent_rank_id, 'shop_id'=>$shopId, 'agent_type'=>3))->getField('superior_ratio');

        //     }

        // }



        $staff_id = $store_info['staff_id'];

        if ($staff_id) {

            $agent_rank_id = M('User')->where(array('user_id'=>$staff_id, 'is_agent'=>2))->getField('agent_rank_id');

            if ($agent_rank_id) {

                $staff_ratio = M('AgentRank')->where(array('agent_rank_id'=>$agent_rank_id, 'shop_id'=>$shopId, 'agent_type'=>2))->getField('superior_ratio');

            }

        }

    }


    $Order->startTrans();

    $data_commission = array();

    // 是否按实付金额计算佣金

    if ($is_order_money) {

        $no_fx_commission = $limit_discount_money = 0;

        foreach($order_item as $v){

            if($v['item_limit_discount_id']){

                $is_commission = intval(M('ItemLimitDiscount')

                    ->where('item_limit_discount_id = '.$v['item_limit_discount_id'])

                    ->getField('is_commission'));

                if($is_commission === 0){

                    $limit_discount_money += $v['current_price'] * $v['num'];

                    continue;

                }

            } elseif ($v['item_miao_id']) {

                $is_commission = M('ItemMiao')->where('item_miao_id = ' . $v['item_miao_id'])->getField('is_commission');

                if (!$is_commission) {

                    $limit_discount_money += $v['current_price'] * $v['num'];

                    continue;

                }

            }



            if (!$v['is_fx_commission']) $no_fx_commission += $v['current_price'] * $v['num'];

        }



        $order_fx_money = $order_info['payment'] - $limit_discount_money - $no_fx_commission;

        if (!$is_post_fee_commission) $order_fx_money -= $order_info['post_fee'];



        if ($order_fx_money < 0) $order_fx_money = 0;

        $payment_msg = '(实付金额('.$order_info['payment'].')';

        if (!$is_post_fee_commission) $payment_msg .= ' - 运费('.$order_info['post_fee'].')';

        if($no_fx_commission >0 || $limit_discount_money >0){

            $payment_msg .= ' - 不返佣金额('.($no_fx_commission + $limit_discount_money).')';

        }

        $payment_msg .= ')';

        $superior_order_commission = $order_fx_money * ($ratio['directly_online_ratio'] / 100);

        $to_order_commission = $order_fx_money * ($ratio['superior_online_ratio'] / 100);

        $three_order_commission = $order_fx_money * ($ratio['three_online_ratio'] / 100);

        $superior_user_calculation = $payment_msg.' * 佣金比例('.($ratio['directly_online_ratio'] / 100).')';

        $top_user_calculation = $payment_msg.' * 佣金比例('.($ratio['superior_online_ratio'] / 100).')';

        $three_user_calculation = $payment_msg.' * 佣金比例('.($ratio['three_online_ratio'] / 100).')';

    } else {

        $superior_user_calculation=$top_user_calculation=$three_user_calculation = '';

        foreach ($order_item as $rs) {

            if($rs['item_limit_discount_id']){

                $is_commission_item = intval(M('ItemLimitDiscount')

                    ->where('item_limit_discount_id = '.$rs['item_limit_discount_id'])

                    ->getField('is_commission'));

                if($is_commission_item === 0){

                    continue;

                }

            } elseif ($rs['item_miao_id']) {

                $is_commission = M('ItemMiao')->where('item_miao_id = ' . $rs['item_miao_id'])->getField('is_commission');

                if (!$is_commission) {

                    continue;

                }

            }



            if ($complain_order_id) {

                $complain_item_num = M('ComplainItem')

                    ->where(array('complain_order_id'=>$complain_order_id,'order_item_id'=>$rs['order_item_id']))

                    ->getField('num');

                if ($complain_item_num) {

                    $rs['num'] -= $complain_item_num;

                    if ($rs['num'] <= 0) continue;

                }

            }



            // 分销商佣金

            if ($rs['is_fx_commission']) {

                //直属上线

                $order_item_commission_superior_user = 0;

                $superior_calculation = '';

                if ($is_superior_agent) {

                    if (!empty($rs['directly_agent_money'])) {

                        $order_item_commission_superior_user = $rs['directly_agent_money'] * $rs['num'];

                        $superior_calculation = '商品分销商等级佣金金额('.$rs['directly_agent_money'].') * 数量('.$rs['num'].')';

                    } elseif (!empty($rs['directly_agent_rate'])) {

                        $order_item_commission_superior_user = ($rs['current_price'] * $rs['num']) * ($rs['directly_agent_rate'] / 100);

                        $superior_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 商品分销商等级佣金比例('.($rs['directly_agent_rate'] / 100).')';

                    } elseif ($rs['directly_money'] > 0) {

                        $order_item_commission_superior_user = $rs['directly_money'] * $rs['num'];

                        $superior_calculation = '商品佣金金额('.$rs['directly_money'].') * 数量('.$rs['num'].')';

                    } elseif ($rs['directly_rate'] > 0) {

                        $order_item_commission_superior_user = ($rs['current_price'] * $rs['num']) * ($rs['directly_rate'] / 100);

                        $superior_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 商品佣金比例('.($rs['directly_rate'] / 100).')';

                    }elseif($order_info['is_general']==0){

                        $order_item_commission_superior_user = ($rs['current_price'] * $rs['num']) * ($ratio['directly_online_ratio'] / 100);

                        $superior_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 分销商佣金比例('.($ratio['directly_online_ratio'] / 100).')';

                    }

                }

                if($superior_user_calculation && $superior_calculation){

                    $superior_user_calculation .= ' + '.$superior_calculation;

                }else{

                    $superior_user_calculation = $superior_calculation;

                }

                //上线上线

                $order_item_commission_top_user = 0;

                $top_calculation = '';

                if ($is_top_agent) {

                    if (!empty($rs['superior_agent_money'])) {

                        $order_item_commission_top_user = $rs['superior_agent_money'] * $rs['num'];

                        $top_calculation = '商品分销商等级佣金金额('.$rs['superior_agent_money'].') * 数量('.$rs['num'].')';

                    } elseif (!empty($rs['superior_agent_rate'])) {

                        $order_item_commission_top_user = ($rs['current_price'] * $rs['num']) * ($rs['superior_agent_rate'] / 100);

                        $top_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 商品分销商等级佣金比例('.($rs['superior_agent_rate'] / 100).')';

                    } elseif ($rs['superior_money'] > 0) {

                        $order_item_commission_top_user = $rs['superior_money'] * $rs['num'];

                        $top_calculation = '商品佣金金额('.$rs['superior_money'].') * 数量('.$rs['num'].')';

                    } elseif ($rs['superior_rate'] > 0) {

                        $order_item_commission_top_user = ($rs['current_price'] * $rs['num']) * ($rs['superior_rate'] / 100);

                        $top_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 商品佣金比例('.($rs['superior_rate'] / 100).')';

                    }elseif($order_info['is_general']==0){

                        $order_item_commission_top_user = ($rs['current_price'] * $rs['num']) * ($ratio['superior_online_ratio'] / 100);

                        $top_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 分销商佣金比例('.($ratio['superior_online_ratio'] / 100).')';

                    }

                }

                if($top_user_calculation && $top_calculation){

                    $top_user_calculation .= ' + '.$top_calculation;

                }else{

                    $top_user_calculation = $top_calculation;

                }

                // 三级上线

                $order_item_commission_three_user = 0;

                $three_calculation = '';

                if ($is_three_agent) {

                    if (!empty($rs['three_agent_money'])) {

                        $order_item_commission_three_user = $rs['three_agent_money'] * $rs['num'];

                        $three_calculation = '商品分销商等级佣金金额('.$rs['three_agent_money'].') * 数量('.$rs['num'].')';

                    } elseif (!empty($rs['three_agent_rate'])) {

                        $order_item_commission_three_user = ($rs['current_price'] * $rs['num']) * ($rs['three_agent_rate'] / 100);

                        $three_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 商品分销商等级佣金比例('.($rs['three_agent_rate'] / 100).')';

                    } elseif ($rs['three_money'] > 0) {

                        $order_item_commission_three_user = $rs['three_money'] * $rs['num'];

                        $three_calculation = '商品佣金金额('.$rs['three_money'].') * 数量('.$rs['num'].')';

                    } elseif ($rs['three_rate'] > 0) {

                        $order_item_commission_three_user = ($rs['current_price'] * $rs['num']) * ($rs['three_rate'] / 100);

                        $three_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 商品佣金比例('.($rs['three_rate'] / 100).')';

                    }elseif($order_info['is_general']==0){

                        $order_item_commission_three_user = ($rs['current_price'] * $rs['num']) * ($ratio['three_online_ratio'] / 100);

                        $three_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 分销商佣金比例('.($ratio['three_online_ratio'] / 100).')';

                    }

                }

                if($three_user_calculation && $three_calculation){

                    $three_user_calculation .= ' + '.$three_calculation;

                }else{

                    $three_user_calculation = $three_calculation;

                }



                $superior_order_commission += $order_item_commission_superior_user;

                $to_order_commission += $order_item_commission_top_user;

                $three_order_commission += $order_item_commission_three_user;

                $order_item_data = array();

                if ($is_superior_agent) {

                    $order_item_data['superior_user_id'] = $user_info['superior_user_id'];

                    $order_item_data['superior_commission'] = $order_item_commission_superior_user;

                }

                if ($is_top_agent) {

                    $order_item_data['top_user_id'] = $user_info['top_user_id'];

                    $order_item_data['top_commission'] = $order_item_commission_top_user;

                }

                if ($is_three_agent) {

                    $order_item_data['three_user_id'] = $user_info['three_user_id'];

                    $order_item_data['three_commission'] = $order_item_commission_three_user;

                }

                D('Order_item')

                    ->where('order_item_id=' . $rs['order_item_id'])

                    ->save($order_item_data);

            }

        }



        // 运费返佣

        if ($is_post_fee_commission && $order_info['post_fee']) {

            if ($is_superior_agent) {

                $superior_order_commission += $order_info['post_fee'] * ($ratio['directly_online_ratio'] / 100);

                $superior_calculation = '运费('.$order_info['post_fee'].') * 分销商佣金比例('.($ratio['directly_online_ratio'] / 100).')';

                if($superior_user_calculation){

                    $superior_user_calculation .= ' + '.$superior_calculation;

                }else{

                    $superior_user_calculation = $superior_calculation;

                }

            }

            if ($is_top_agent) {

                $to_order_commission += $order_info['post_fee'] * ($ratio['superior_online_ratio'] / 100);

                $top_calculation = '运费('.$order_info['post_fee'].') * 分销商佣金比例('.($ratio['superior_online_ratio'] / 100).')';

                if($top_user_calculation){

                    $top_user_calculation .= ' + '.$top_calculation;

                }else{

                    $top_user_calculation = $top_calculation;

                }

            }

            if ($is_three_agent) {

                $three_order_commission += $order_info['post_fee'] * ($ratio['three_online_ratio'] / 100);

                $three_calculation = '运费('.$order_info['post_fee'].') * 分销商佣金比例('.($ratio['three_online_ratio'] / 100).')';

                if($three_user_calculation){

                    $three_user_calculation .= ' + '.$three_calculation;

                }else{

                    $three_user_calculation = $three_calculation;

                }

            }

        }

    }



    // 代理商佣金计算

    if ($is_dls_money) {

        $no_dl_commission = $limit_discount_money = 0;

        foreach($order_item as $v){

            if($v['item_limit_discount_id']){

                $is_commission = intval(M('ItemLimitDiscount')

                    ->where('item_limit_discount_id = '.$v['item_limit_discount_id'])

                    ->getField('is_commission'));

                if($is_commission === 0){

                    $limit_discount_money += $v['current_price'] * $v['num'];

                    continue;

                }

            } elseif ($v['item_miao_id']) {

                $is_commission = M('ItemMiao')->where('item_miao_id = ' . $v['item_miao_id'])->getField('is_commission');
                if (!$is_commission) {
                    $limit_discount_money += $v['current_price'] * $v['num'];
                    continue;
                }

            }

            if (!$v['is_dl_commission']) $no_dl_commission += $v['current_price'] * $v['num'];

        }

        $order_dl_money = $order_info['payment'] - $limit_discount_money - $no_dl_commission;

        if (!$is_post_fee_commission) $order_dl_money -= $order_info['post_fee'];

        if ($order_dl_money < 0) $order_dl_money = 0;



        $payment_dl_msg = '(实付金额('.$order_info['payment'].')';

        if (!$is_post_fee_commission) $payment_dl_msg .= ' - 运费('.$order_info['post_fee'].')';

        if($no_dl_commission >0 || $limit_discount_money >0){

            $payment_dl_msg .= ' - 不返佣金额('.($no_dl_commission + $limit_discount_money).')';

        }

        $payment_dl_msg .= ')';

        // 代理商佣金

        if (isset($superior_dls_ratio)) $superior_dls_commission = $order_dl_money * ($superior_dls_ratio / 100);

        if (isset($top_dls_ratio)) $top_dls_commission = $order_dl_money * ($top_dls_ratio / 100);

        if (isset($three_dls_ratio)) $three_dls_commission = $order_dl_money * ($three_dls_ratio / 100);

        if (isset($four_dls_ratio)) $four_dls_commission = $order_dl_money * ($four_dls_ratio / 100);



        if (isset($superior_dls_ratio)) $superior_dls_calculation = $payment_dl_msg.' * 佣金比例('.($superior_dls_ratio / 100).')';

        if (isset($top_dls_ratio)) $top_dls_calculation = $payment_dl_msg.' * 佣金比例('.($top_dls_ratio / 100).')';

        if (isset($three_dls_ratio)) $three_dls_calculation = $payment_dl_msg.' * 佣金比例('.($three_dls_ratio / 100).')';

        if (isset($four_dls_ratio)) $four_dls_calculation = $payment_dl_msg.' * 佣金比例('.($four_dls_ratio / 100).')';



    } else {

        $superior_dls_commission = 0;

        $top_dls_commission = 0;

        $three_dls_commission = 0;

        $superior_dls_calculation = $top_dls_calculation = $three_dls_calculation = '';

        foreach ($order_item as $rs) {

            if($rs['item_limit_discount_id']){

                $is_commission_item = intval(M('ItemLimitDiscount')

                    ->where('item_limit_discount_id = '.$rs['item_limit_discount_id'])

                    ->getField('is_commission'));

                if($is_commission_item === 0){

                    continue;

                }

            } elseif ($rs['item_miao_id']) {

                $is_commission = M('ItemMiao')->where('item_miao_id = ' . $rs['item_miao_id'])->getField('is_commission');

                if (!$is_commission) {

                    continue;

                }

            }



            if ($complain_order_id) {

                $complain_item_num = M('ComplainItem')

                    ->where(array('complain_order_id'=>$complain_order_id,'order_item_id'=>$rs['order_item_id']))

                    ->getField('num');

                if ($complain_item_num) {

                    $rs['num'] -= $complain_item_num;

                    if ($rs['num'] <= 0) continue;

                }

            }



            // 代理商佣金

            if ($rs['is_dl_commission']) {

                if($order_info['coupon_repurchase_price']){

                    $repurchase_info = M('ItemRepurchase')->where('item_id = '.$rs['item_id'].' AND shop_id = '.$shopId)->find();

                }

                if(!empty($repurchase_info)){

                    $dls_commission_money = $repurchase_info;

                }else{

                    $dls_commission_money = M('ItemDls')

                        ->where('item_id = '.$rs['item_id'])

                        ->find();

                }

                // 四级代理商

                $four_d_calculation = '';

                if($dls_commission_money['dls_four_money'] >0){

                    $item_four_dls = $dls_commission_money['dls_four_money']*$rs['num'];

                    $four_d_calculation = '商品佣金金额('.$dls_commission_money['dls_four_money'].') * 数量('.$rs['num'].')';

                }elseif($dls_commission_money['dls_four_rate'] >0){

                    $item_four_dls = ($rs['current_price'] * $rs['num']) * ($dls_commission_money['dls_four_rate'] / 100);

                    $four_d_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 商品佣金比例('.($dls_commission_money['dls_four_rate'] / 100).')';

                }elseif($order_info['is_general']==0){

                    $item_four_dls = ($rs['current_price'] * $rs['num']) * ($four_dls_ratio / 100);

                    $four_d_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 代理商佣金比例('.($four_dls_ratio / 100).')';

                }

                $four_dls_commission += $item_four_dls;

                if($four_dls_calculation && $four_d_calculation){

                    $four_dls_calculation .= ' + '.$four_d_calculation;

                }else{

                    $four_dls_calculation = $four_d_calculation;

                }

                // 三级代理商

                $three_d_calculation = '';

                if($dls_commission_money['dls_superior_money'] >0){

                    $item_three_dls = $dls_commission_money['dls_superior_money']*$rs['num'];

                    $three_d_calculation = '商品佣金金额('.$dls_commission_money['dls_superior_money'].') * 数量('.$rs['num'].')';

                    if (!$dls_info['four_dls_id'] && $dls_commission_money['is_get_lower']) {

                        $item_three_dls += $item_four_dls;

                        $three_d_calculation .= ' + 下级代理商佣金('.$item_four_dls.')';

                    }

                }elseif($dls_commission_money['dls_superior_rate'] >0){

                    $item_three_dls = ($rs['current_price'] * $rs['num']) * ($dls_commission_money['dls_superior_rate'] / 100);

                    $three_d_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 商品佣金比例('.($dls_commission_money['dls_superior_rate'] / 100).')';

                    if (!$dls_info['four_dls_id'] && $dls_commission_money['is_get_lower']) {

                        $item_three_dls += $item_four_dls;

                        $three_d_calculation .= ' + 下级代理商佣金('.$item_four_dls.')';

                    }

                }elseif($order_info['is_general']==0){

                    $item_three_dls = ($rs['current_price'] * $rs['num']) * ($three_dls_ratio / 100);

                    $three_d_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 代理商佣金比例('.($three_dls_ratio / 100).')';

                }

                $three_dls_commission += $item_three_dls;

                if($three_dls_calculation && $three_d_calculation){

                    $three_dls_calculation .= ' + '.$three_d_calculation;

                }else{

                    $three_dls_calculation = $three_d_calculation;

                }

                // 二级代理商

                $top_d_calculation = '';

                if($dls_commission_money['dls_superior_money'] >0){

                    $item_top_dls = $dls_commission_money['dls_superior_money']*$rs['num'];

                    $top_d_calculation = '商品佣金金额('.$dls_commission_money['dls_superior_money'].') * 数量('.$rs['num'].')';

                    if (!$dls_info['three_dls_id'] && $dls_commission_money['is_get_lower']) {

                        $item_top_dls += $item_three_dls;

                        $top_d_calculation .= ' + 下级代理商佣金('.$item_three_dls.')';

                    }

                }elseif($dls_commission_money['dls_superior_rate'] >0){

                    $item_top_dls = ($rs['current_price'] * $rs['num']) * ($dls_commission_money['dls_superior_rate'] / 100);

                    $top_d_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 商品佣金比例('.($dls_commission_money['dls_superior_rate'] / 100).')';

                    if (!$dls_info['three_dls_id'] && $dls_commission_money['is_get_lower']) {

                        $item_top_dls += $item_three_dls;

                        $top_d_calculation .= ' + 下级代理商佣金('.$item_three_dls.')';

                    }

                }elseif($order_info['is_general']==0){

                    $item_top_dls = ($rs['current_price'] * $rs['num']) * ($top_dls_ratio / 100);

                    $top_d_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 代理商佣金比例('.($top_dls_ratio / 100).')';

                }

                $top_dls_commission += $item_top_dls;

                if($top_dls_calculation && $top_d_calculation){

                    $top_dls_calculation .= ' + '.$top_d_calculation;

                }else{

                    $top_dls_calculation = $top_d_calculation;

                }

                // 一级代理商

                $superior_d_calculation = '';

                if($dls_commission_money['dls_directly_money'] >0){

                    $item_superior_dls = $dls_commission_money['dls_directly_money']*$rs['num'];

                    $superior_d_calculation = '商品佣金金额('.$dls_commission_money['dls_directly_money'].') * 数量('.$rs['num'].')';

                    if (!$dls_info['top_dls_id'] && $dls_commission_money['is_get_lower']) {

                        $item_superior_dls += $item_top_dls;

                        $superior_d_calculation .= ' + 下级代理商佣金('.$item_top_dls.')';

                    }

                }elseif($dls_commission_money['dls_directly_rate'] >0){

                    $item_superior_dls = ($rs['current_price'] * $rs['num']) * ($dls_commission_money['dls_directly_rate'] / 100);

                    $superior_d_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 商品佣金比例('.($dls_commission_money['dls_directly_rate'] / 100).')';

                    if (!$dls_info['top_dls_id'] && $dls_commission_money['is_get_lower']) {

                        $item_superior_dls += $item_top_dls;

                        $superior_d_calculation .= ' + 下级代理商佣金('.$item_top_dls.')';

                    }

                }elseif($order_info['is_general']==0){

                    $item_superior_dls = ($rs['current_price'] * $rs['num']) * ($superior_dls_ratio / 100);

                    $superior_d_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 代理商佣金比例('.($superior_dls_ratio / 100).')';

                }

                $superior_dls_commission += $item_superior_dls;



                if($superior_dls_calculation && $superior_d_calculation){

                    $superior_dls_calculation .= ' + '.$superior_d_calculation;

                }else{

                    $superior_dls_calculation = $superior_d_calculation;

                }



            }



        }
        // 运费返佣
        if ($is_post_fee_commission && $order_info['post_fee']) {

            if ($dls_info['superior_dls_id']) {

                $superior_dls_commission += $order_info['post_fee'] * ($superior_dls_ratio / 100);

                $superior_d_calculation = '运费('.$order_info['post_fee'].') * 代理商佣金比例('.($superior_dls_ratio / 100).')';

                if($superior_dls_calculation){

                    $superior_dls_calculation .= ' + '.$superior_d_calculation;

                }else{

                    $superior_dls_calculation = $superior_d_calculation;

                }

            }

            if ($dls_info['top_dls_id']) {

                $top_dls_commission += $order_info['post_fee'] * ($top_dls_ratio / 100);

                $top_d_calculation = '运费('.$order_info['post_fee'].') * 代理商佣金比例('.($top_dls_ratio / 100).')';

                if($top_dls_calculation){

                    $top_dls_calculation .= ' + '.$top_d_calculation;

                }else{

                    $top_dls_calculation = $top_d_calculation;

                }

            }

            if ($dls_info['three_dls_id']) {

                $three_dls_commission += $order_info['post_fee'] * ($three_dls_ratio / 100);

                $three_d_calculation = '运费('.$order_info['post_fee'].') * 代理商佣金比例('.($three_dls_ratio / 100).')';

                if($three_dls_calculation){

                    $three_dls_calculation .= ' + '.$three_d_calculation;

                }else{

                    $three_dls_calculation = $three_d_calculation;

                }

            }

            if ($dls_info['four_dls_id']) {

                $four_dls_commission += $order_info['post_fee'] * ($four_dls_ratio / 100);

                $four_d_calculation = '运费('.$order_info['post_fee'].') * 代理商佣金比例('.($four_dls_ratio / 100).')';

                if($tfour_dls_calculation){

                    $four_dls_calculation .= ' + '.$four_d_calculation;

                }else{

                    $four_dls_calculation = $four_d_calculation;

                }

            }

        }

    }
    //新门店规则
    if($order_info['is_general']==0 && $order_info['self_address_id']>0 && empty($order_info['fund_fee'])){
        header("content-type:text/html;charset=utf-8");
        $store_id_new = M('SelfAddress')->where(array('self_address_id'=>$order_info['self_address_id']))->getField('type_id');
        $store_ratio = M('AgentRank')->where(array('title'=>'门店1','agent_type'=>3))->getField('superior_ratio');
        // echo $store_ratio;
        if ($store_ratio){
            $no_fx_commission = $limit_discount_money = 0;
            foreach ($order_item as $v) {
                if ($v['item_limit_discount_id']) {
                    $is_commission = intval(M('ItemLimitDiscount')
                        ->where('item_limit_discount_id = ' . $v['item_limit_discount_id'])
                        ->getField('is_commission'));
                    if ($is_commission === 0) {
                        $limit_discount_money += $v['current_price'] * $v['num'];
                        continue;
                    }
                } elseif ($v['item_miao_id']) {
                    $is_commission = M('ItemMiao')->where('item_miao_id = ' . $v['item_miao_id'])->getField('is_commission');
                    if (!$is_commission) {
                        $limit_discount_money += $v['current_price'] * $v['num'];
                        continue;
                    }
                }
            }
            $order_fx_money = $order_info['payment'] - $limit_discount_money - $no_fx_commission;
            if (!$is_post_fee_commission) $order_fx_money -= $order_info['post_fee'];
            if ($order_fx_money < 0) $order_fx_money = 0;

            $payment_msg = '(实付金额(' . $order_info['payment'] . ')';

            if (!$is_post_fee_commission) $payment_msg .= ' - 运费(' . $order_info['post_fee'] . ')';

            if ($no_fx_commission > 0 || $limit_discount_money > 0) {

                $payment_msg .= ' - 不返佣金额(' . ($no_fx_commission + $limit_discount_money) . ')';

            }
            $payment_msg .= ')';
            $store_commission = $order_fx_money * ($store_ratio / 100);
            $store_calculation = $payment_msg . ' * 佣金比例(' . ($store_ratio / 100) . ')';
        }
    }
    // 计算门店佣金
    
    if ($store_id) {

        if ($is_store_money) {

            if ($store_ratio) {

                $no_fx_commission = $limit_discount_money = 0;

                foreach ($order_item as $v) {

                    if ($v['item_limit_discount_id']) {

                        $is_commission = intval(M('ItemLimitDiscount')

                            ->where('item_limit_discount_id = ' . $v['item_limit_discount_id'])

                            ->getField('is_commission'));

                        if ($is_commission === 0) {

                            $limit_discount_money += $v['current_price'] * $v['num'];

                            continue;

                        }

                    } elseif ($v['item_miao_id']) {

                        $is_commission = M('ItemMiao')->where('item_miao_id = ' . $v['item_miao_id'])->getField('is_commission');

                        if (!$is_commission) {

                            $limit_discount_money += $v['current_price'] * $v['num'];

                            continue;

                        }

                    }

                }



                $order_fx_money = $order_info['payment'] - $limit_discount_money - $no_fx_commission;

                if (!$is_post_fee_commission) $order_fx_money -= $order_info['post_fee'];



                if ($order_fx_money < 0) $order_fx_money = 0;

                $payment_msg = '(实付金额(' . $order_info['payment'] . ')';

                if (!$is_post_fee_commission) $payment_msg .= ' - 运费(' . $order_info['post_fee'] . ')';

                if ($no_fx_commission > 0 || $limit_discount_money > 0) {

                    $payment_msg .= ' - 不返佣金额(' . ($no_fx_commission + $limit_discount_money) . ')';

                }

                $payment_msg .= ')';

                $store_commission = $order_fx_money * ($store_ratio / 100);

                $store_calculation = $payment_msg . ' * 佣金比例(' . ($store_ratio / 100) . ')';

            }

        } else {

            $store_commission = 0;

            $store_calculation = '';

            foreach ($order_item as $rs) {

                if($rs['item_limit_discount_id']){

                    $is_commission_item = intval(M('ItemLimitDiscount')

                        ->where('item_limit_discount_id = '.$rs['item_limit_discount_id'])

                        ->getField('is_commission'));

                    if($is_commission_item === 0){

                        continue;

                    }

                } elseif ($rs['item_miao_id']) {

                    $is_commission = M('ItemMiao')->where('item_miao_id = ' . $rs['item_miao_id'])->getField('is_commission');

                    if (!$is_commission) {

                        continue;

                    }

                }



                if ($complain_order_id) {

                    $complain_item_num = M('ComplainItem')

                        ->where(array('complain_order_id'=>$complain_order_id,'order_item_id'=>$rs['order_item_id']))

                        ->getField('num');

                    if ($complain_item_num) {

                        $rs['num'] -= $complain_item_num;

                        if ($rs['num'] <= 0) continue;

                    }

                }



                // 门店佣金

                if ($rs['is_store_commission']) {

                    if($order_info['coupon_repurchase_price']){

                        $repurchase_info = M('ItemRepurchase')->where('item_id = '.$rs['item_id'].' AND shop_id = '.$shopId)->find();

                    }

                    if(!empty($repurchase_info)){

                        $dls_commission_money = $repurchase_info;

                    }else{

                        $dls_commission_money = M('ItemDls')

                            ->where('item_id = '.$rs['item_id'])

                            ->find();

                    }

                    if($dls_commission_money['store_money'] >0){

                        $item_three_dls = $dls_commission_money['store_money']*$rs['num'];

                        $three_d_calculation = '商品佣金金额('.$dls_commission_money['store_money'].') * 数量('.$rs['num'].')';

                    }elseif($dls_commission_money['store_rate'] >0){

                        $item_three_dls = ($rs['current_price'] * $rs['num']) * ($dls_commission_money['store_rate'] / 100);

                        $three_d_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 商品佣金比例('.($dls_commission_money['store_rate'] / 100).')';

                    }else{

                        $item_three_dls = ($rs['current_price'] * $rs['num']) * ($three_dls_ratio / 100);

                        $three_d_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 门店佣金比例('.($store_ratio / 100).')';

                    }

                    $store_commission += $item_three_dls;

                    if($store_calculation && $three_d_calculation){

                        $store_calculation .= ' + '.$three_d_calculation;

                    }else{

                        $store_calculation = $three_d_calculation;

                    }

                }



            }



            // 运费返佣

            if ($is_post_fee_commission && $order_info['post_fee']) {

                $store_commission += $order_info['post_fee'] * ($store_ratio / 100);

                $three_d_calculation = '运费('.$order_info['post_fee'].') * 门店佣金比例('.($store_ratio / 100).')';

                if($store_calculation){

                    $store_calculation .= ' + '.$three_d_calculation;

                }else{

                    $store_calculation = $three_d_calculation;

                }

            }



        }

    }



    // 计算员工佣金

    if ($staff_id) {

        if ($is_staff_money) {

            if ($staff_ratio) {

                $no_fx_commission = $limit_discount_money = 0;

                foreach ($order_item as $v) {

                    if ($v['item_limit_discount_id']) {

                        $is_commission = intval(M('ItemLimitDiscount')

                            ->where('item_limit_discount_id = ' . $v['item_limit_discount_id'])

                            ->getField('is_commission'));

                        if ($is_commission === 0) {

                            $limit_discount_money += $v['current_price'] * $v['num'];

                            continue;

                        }

                    } elseif ($v['item_miao_id']) {

                        $is_commission = M('ItemMiao')->where('item_miao_id = ' . $v['item_miao_id'])->getField('is_commission');

                        if (!$is_commission) {

                            $limit_discount_money += $v['current_price'] * $v['num'];

                            continue;

                        }

                    }

                }



                $order_fx_money = $order_info['payment'] - $limit_discount_money - $no_fx_commission;

                if (!$is_post_fee_commission) $order_fx_money -= $order_info['post_fee'];



                if ($order_fx_money < 0) $order_fx_money = 0;

                $payment_msg = '(实付金额(' . $order_info['payment'] . ')';

                if (!$is_post_fee_commission) $payment_msg .= ' - 运费(' . $order_info['post_fee'] . ')';

                if ($no_fx_commission > 0 || $limit_discount_money > 0) {

                    $payment_msg .= ' - 不返佣金额(' . ($no_fx_commission + $limit_discount_money) . ')';

                }

                $payment_msg .= ')';

                $staff_commission = $order_fx_money * ($staff_ratio / 100);

                $staff_calculation = $payment_msg . ' * 佣金比例(' . ($staff_ratio / 100) . ')';

            }

        } else {

            $staff_commission = 0;

            $staff_calculation = '';

            foreach ($order_item as $rs) {

                if($rs['item_limit_discount_id']){

                    $is_commission_item = intval(M('ItemLimitDiscount')

                        ->where('item_limit_discount_id = '.$rs['item_limit_discount_id'])

                        ->getField('is_commission'));

                    if($is_commission_item === 0){

                        continue;

                    }

                } elseif ($rs['item_miao_id']) {

                    $is_commission = M('ItemMiao')->where('item_miao_id = ' . $rs['item_miao_id'])->getField('is_commission');

                    if (!$is_commission) {

                        continue;

                    }

                }



                if ($complain_order_id) {

                    $complain_item_num = M('ComplainItem')

                        ->where(array('complain_order_id'=>$complain_order_id,'order_item_id'=>$rs['order_item_id']))

                        ->getField('num');

                    if ($complain_item_num) {

                        $rs['num'] -= $complain_item_num;

                        if ($rs['num'] <= 0) continue;

                    }

                }



                // 员工佣金

                if ($rs['is_staff_commission']) {

                    if($order_info['coupon_repurchase_price']){

                        $repurchase_info = M('ItemRepurchase')->where('item_id = '.$rs['item_id'].' AND shop_id = '.$shopId)->find();

                    }

                    if(!empty($repurchase_info)){

                        $dls_commission_money = $repurchase_info;

                    }else{

                        $dls_commission_money = M('ItemDls')

                            ->where('item_id = '.$rs['item_id'])

                            ->find();

                    }

                    if($dls_commission_money['staff_money'] >0){

                        $item_three_dls = $dls_commission_money['staff_money']*$rs['num'];

                        $three_d_calculation = '商品佣金金额('.$dls_commission_money['staff_money'].') * 数量('.$rs['num'].')';

                    }elseif($dls_commission_money['staff_rate'] >0){

                        $item_three_dls = ($rs['current_price'] * $rs['num']) * ($dls_commission_money['staff_rate'] / 100);

                        $three_d_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 商品佣金比例('.($dls_commission_money['staff_rate'] / 100).')';

                    }else{

                        $item_three_dls = ($rs['current_price'] * $rs['num']) * ($three_dls_ratio / 100);

                        $three_d_calculation = '价格('.$rs['current_price'].') * 数量('.$rs['num'].') * 员工佣金比例('.($staff_ratio / 100).')';

                    }

                    $staff_commission += $item_three_dls;

                    if($staff_calculation && $three_d_calculation){

                        $staff_calculation .= ' + '.$three_d_calculation;

                    }else{

                        $staff_calculation = $three_d_calculation;

                    }

                }



            }



            // 运费返佣

            if ($is_post_fee_commission && $order_info['post_fee']) {

                $staff_commission += $order_info['post_fee'] * ($staff_ratio / 100);

                $three_d_calculation = '运费('.$order_info['post_fee'].') * 员工佣金比例('.($staff_ratio / 100).')';

                if($staff_calculation){

                    $staff_calculation .= ' + '.$three_d_calculation;

                }else{

                    $staff_calculation = $three_d_calculation;

                }

            }



        }

    }



    $order_data = array();

    if($is_superior_agent){

        $order_data['superior_user_id'] = $user_info['superior_user_id'];

        $order_data['superior_commission'] = $superior_order_commission;

        $order_data['have_balance'] = 1;

        $data_commission['superior_user_id'] = $user_info['superior_user_id'];

        $data_commission['superior_user_calculation'] = $superior_user_calculation;

    }

    if($is_top_agent){

        $order_data['top_user_id'] = $user_info['top_user_id'];

        $order_data['top_commission'] = $to_order_commission;

        $order_data['have_balance'] = 1;

        $data_commission['top_user_id'] = $user_info['top_user_id'];

        $data_commission['top_user_calculation'] = $top_user_calculation;

    }

    if($is_three_agent){

        $order_data['three_user_id'] = $user_info['three_user_id'];

        $order_data['three_commission'] = $three_order_commission;

        $order_data['have_balance'] = 1;

        $data_commission['three_user_id'] = $user_info['three_user_id'];

        $data_commission['three_user_calculation'] = $three_user_calculation;

    }



    // 代理商佣金

    if ($dls_info['superior_dls_id']) {

        if (!isset($superior_dls_commission)) $superior_dls_commission = 0;

        $order_data['superior_dls_id'] = $dls_info['superior_dls_id'];

        $order_data['superior_dls_commission'] = $superior_dls_commission;

        $order_data['have_balance'] = 1;

        $data_commission['superior_dls_id'] = $dls_info['superior_dls_id'];

        $data_commission['superior_dls_calculation'] = $superior_dls_calculation;

    }

    if ($dls_info['top_dls_id']) {

        if (!isset($top_dls_commission)) $top_dls_commission = 0;

        $order_data['top_dls_id'] = $dls_info['top_dls_id'];

        $order_data['top_dls_commission'] = $top_dls_commission;

        $order_data['have_balance'] = 1;

        $data_commission['top_dls_id'] = $dls_info['top_dls_id'];

        $data_commission['top_dls_calculation'] = $top_dls_calculation;

    }

    if ($dls_info['three_dls_id']) {

        if (!isset($three_dls_commission)) $three_dls_commission = 0;

        $order_data['three_dls_id'] = $dls_info['three_dls_id'];

        $order_data['three_dls_commission'] = $three_dls_commission;

        $order_data['have_balance'] = 1;

        $data_commission['three_dls_id'] = $user_info['three_dls_id'];

        $data_commission['three_dls_calculation'] = $three_dls_calculation;

    }

    if ($dls_info['four_dls_id']) {

        if (!isset($four_dls_commission)) $four_dls_commission = 0;

        $order_data['four_dls_id'] = $dls_info['four_dls_id'];

        $order_data['four_dls_commission'] = $four_dls_commission;

        $order_data['have_balance'] = 1;

        $data_commission['four_dls_id'] = $user_info['four_dls_id'];

        $data_commission['four_dls_calculation'] = $four_dls_calculation;

    }



    // 代理商自己下单,是否拿代理佣金

    $not_dls_self_commission = config('not_dls_self_commission');

    if ($not_dls_self_commission) {

        if ($dls_info['superior_dls_id'] == $order_info['user_id']) {

            $order_data['superior_dls_commission'] = $order_data['top_dls_commission'] = $order_data['three_dls_commission'] = $order_data['four_dls_commission'] = 0;

            $data_commission['superior_dls_calculation'] = $data_commission['top_dls_calculation'] = $data_commission['three_dls_calculation'] = $data_commission['four_dls_calculation'] ='';

        }

        elseif ($dls_info['top_dls_id'] == $order_info['user_id']) {

            $order_data['top_dls_commission'] = $order_data['three_dls_commission'] = $order_data['four_dls_commission'] = 0;

            $data_commission['top_dls_calculation'] = $data_commission['three_dls_calculation'] = $data_commission['four_dls_calculation'] ='';

        }

        elseif ($dls_info['three_dls_id'] == $order_info['user_id']) {
            $order_data['three_dls_commission'] = $order_data['four_dls_commission'] = 0;
            $data_commission['three_dls_calculation'] = $data_commission['four_dls_calculation'] ='';
        }elseif($dls_info['three_dls_id'] == $order_info['user_id']){
            $order_data['four_dls_commission'] = 0;
            $data_commission['four_dls_calculation'] = '';
        }
    }
    // if ($store_id) {

    //     if (!isset($store_commission)) $store_commission = 0;

    //     $order_data['store_id'] = $store_id;

    //     $order_data['store_commission'] = $store_commission;

    //     $order_data['have_balance'] = 1;

    //     $data_commission['store_id'] = $store_id;

    //     $data_commission['store_calculation'] = $store_calculation;

    // }
    if($store_id_new){
        if (!isset($store_commission)) $store_commission = 0;
        $order_data['store_id'] = $store_id_new;
        $order_data['store_commission'] = $store_commission;
        $order_data['have_balance'] = 1;
        $data_commission['store_id'] = $store_id_new;
        $data_commission['store_calculation'] = $store_calculation;
    }


    if ($staff_id) {

        if (!isset($staff_commission)) $staff_commission = 0;

        $order_data['staff_id'] = $staff_id;

        $order_data['staff_commission'] = $staff_commission;

        $order_data['have_balance'] = 1;

        $data_commission['staff_id'] = $staff_id;

        $data_commission['staff_calculation'] = $staff_calculation;

    }



    $oid = $Order -> where('order_id='.$order_info['order_id']) -> save($order_data);

    if($oid === false){

        $Order->rollback();

    }else{

        $Order->commit();

        $OrderCommission = M('OrderCommission');

        $data_commission_map= array('order_id'=>$order_id,'shop_id'=>$shopId);

        if($OrderCommission->where($data_commission_map)->getField(1)){

            $OrderCommission->where($data_commission_map)->save($data_commission);

        }else{

            if($data_commission['superior_user_calculation'] || $data_commission['top_user_calculation'] || $data_commission['three_user_calculation'] || $data_commission['superior_dls_calculation'] || $data_commission['top_dls_calculation'] || $data_commission['three_dls_calculation'] || $data_commission['store_calculation'] || $data_commission['staff_calculation']){

                $data_commission = array_merge($data_commission_map,$data_commission);

                $OrderCommission->add($data_commission);

            }

        }

    }

    return true;

}



/**

 * 计算分销商等级的佣金比例

 *  

 */

function ratio_commission($user_info,$default_ratio){

    $ratio = array();

    $ratio['directly_online_ratio'] = agent_ratio($user_info['superior_user_id'],'directly_online_ratio',$default_ratio);

    $ratio['superior_online_ratio'] = agent_ratio($user_info['top_user_id'],'superior_online_ratio',$default_ratio);

    $ratio['three_online_ratio'] =    agent_ratio($user_info['three_user_id'],'three_online_ratio',$default_ratio);

    return $ratio;

}



/**

 * 计算分销商等级的佣金比例

 *  

 */

function agent_ratio($user_id,$type,$default_ratio){

    $User = M('User');$AgentRank = M('AgentRank');

    $user_info = $User->where('user_id = '.$user_id)->field('agent_rank_id,shop_id')->find();

    $ratio = 0;

    if($user_info['agent_rank_id']){

        if($type == 'directly_online_ratio'){

            $superior_ratio = $AgentRank->where('agent_rank_id  = '.$user_info['agent_rank_id'].' AND shop_id = '.$user_info['shop_id'])->getField('superior_ratio');

        }elseif($type == 'superior_online_ratio'){

            $superior_ratio = $AgentRank->where('agent_rank_id  = '.$user_info['agent_rank_id'].' AND shop_id = '.$user_info['shop_id'])->getField('top_ratio');

        }elseif($type == 'three_online_ratio'){

            $superior_ratio = $AgentRank->where('agent_rank_id  = '.$user_info['agent_rank_id'].' AND shop_id = '.$user_info['shop_id'])->getField('three_ratio');

        }

        $ratio= $superior_ratio?$superior_ratio:$default_ratio[$type];

    }else{

        $ratio = $default_ratio[$type];

    }



    return $ratio;

}



/**

 * 获取权限列表

 *  

 */

function get_all_priv_list($priv_str){

    $priv_str_arr = explode(',', $priv_str);

    require (APP_PATH.'Common/Conf/priv.php');



    if(!$priv_str){

        return array();

    }



    $my_menu_file = array();

    foreach ($admin_menu_file as $k => $v) { //$v = array('id' => 'XX', 'name' => 'XX', 'mod_do_url' => '', 'in_menu' => '', 0=>array(),1=>Array()...);

        if (!is_array($v)) {

            continue;

        }

        if (in_array($v['id'], $priv_str_arr)) {

            $my_menu_file[$k] = array('id' => $v['id'], 'name' => $v['name'], 'mod_do_url' => $v['mod_do_url'], 'in_menu' => $v['in_menu'],'in_home'=>isset($v['in_home'])?$v['in_home']:'');

        } else {

            continue;

        }

        foreach ($v['menu_list'] as $k1 => $v1) { //有效的（即是数组的值）项$n = array('id' => 'XX', 'name' => 'XX', 'mod_do_url' => '/XX-acp_XX', 'in_menu' => '');

            if (!is_array($v1)) {

                continue;

            }

            foreach($v1 as $m=>$n){

                if (in_array($n['id'], $priv_str_arr)) {

                    $my_menu_file[$k]['menu_list'][$k1][$m] = array('id' => $n['id'], 'name' => $n['name'], 'mod_do_url' => $n['mod_do_url'], 'in_menu' => $n['in_menu'],'in_home'=>isset($n['in_home'])?$n['in_home']:'');

                }

            }

        }

    }

    return $my_menu_file;

}

/**

 * 获取版本权限

 *  

 */

/*function get_version_priv($priv_str){

    $priv_str_arr = explode(',', $priv_str);

    require (APP_PATH.'Common/Conf/priv.php');



    if(!$priv_str){

        return array();

    }



    foreach ($admin_menu_file as $k => $v) { //$v = array('id' => 'XX', 'name' => 'XX', 'mod_do_url' => '', 'in_menu' => '', 0=>array(),1=>Array()...);

        if (!is_array($v)) {

            continue;

        }

        if (!in_array($v['id'], $priv_str_arr)) {

            unset($admin_menu_file[$k]);

        }

    }

    return $admin_menu_file;

}*/

/**

 * 验证权限

 *  

 */

function check_priv_list($my_menu_file, $priv_str, $mod_do_url, $nz_curpage = false) {



    $priv_str_arr = explode(',', $priv_str);



    $have_priv = false;

    $have_find = false;



    foreach ($my_menu_file as $k => $v) {

        if (isset($v['menu_list']) && is_array($v['menu_list'])) {

            foreach ($v['menu_list'] as $k1 => $v1) {

                foreach($v1 as $m=>$n){

                    $count = explode('/',$n['mod_do_url']);

                    if(count($count) >3){

                        $url = '/'.$count[1].'/'.$count[2];

                        if(strtolower($mod_do_url) == '/user/export/type/2'){

                            $url = $n['mod_do_url'];

                        }

                        if (is_array($n) && strtolower($url) == strtolower($mod_do_url)) {

                            if (in_array($n['id'], $priv_str_arr)) {

                                $have_priv = true;

                            }



                            $have_find = true;

                            break;

                        }

                    }else{

                        if (is_array($n) && strtolower($n['mod_do_url']) == strtolower($mod_do_url)) {

                            if (in_array($n['id'], $priv_str_arr)) {

                                $have_priv = true;

                            }



                            $have_find = true;

                            break;

                        }

                    }

                    if (is_array($n) && strtolower($n['mod_do_url']) == strtolower($mod_do_url)) {

                        if (in_array($n['id'], $priv_str_arr)) {

                            $have_priv = true;

                        }



                        $have_find = true;

                        break;

                    }

                }

            }

        }

        if ($have_find) {

            break;

        }

    }

    return $have_priv;

}

/**

 * 验证ajax权限

 *  

 */

function check_ajax_priv_list()

{

    require (APP_PATH.'Common/Conf/ajax_priv.php');

    foreach ($admin_ajax_file AS $k => $v)

    {

        foreach ($v AS $key => $value)

        {

            if (strtolower(CONTROLLER_NAME) == strtolower($value['mod']) && strtolower(ACTION_NAME) == strtolower($value['do']))

            {

                return true;

            }

        }

    }



    return false;

}





/**

 * 支付类型

 * @param 类型（1：支付宝 2：微信支付，3：网银）

 *  

 */

function get_alipay_type($type){

    switch ($type) {

        case 1:

            $info = '支付宝';

            break;

        case 2:

            $info = '微信支付';

            break;

        case 3:

            $info = '京东支付';

            break;

        case 4:

            $info = '银联支付';

            break;

        default:

            $info = '';

    }

    return $info;

}



/**

 * 支付类型

 * @param 类型（1：中国很行 2：中国农业很行，3：中国建设银行 4:中国招商银行 5:中国工商银行 6:中国邮政 7:交通银行 8:中国民生银行 9:广东发展银行）

 *  

 */

function get_bank_type($type){

    $n=M('Bank')->Where('bank_id='.$type.' AND type>0 AND shop_id='.SHOP_ID)->getField('bank_name');

    // switch ($type) {

    //     case 1:

    //         $info = '中国银行';

    //         break;

    //     case 2:

    //         $info = '中国农业银行';

    //         break;

    //     case 3:

    //         $info = '中国建设银行';

    //         break;

    //     case 4:

    //         $info = '中国招商银行';

    //         break;

    //     case 5:

    //         $info = '中国工商银行';

    //         break;

    //     case 6:

    //         $info = '中国邮政';

    //         break;

    //     case 7:

    //         $info = '交通银行';

    //         break;

    //     case 8:

    //         $info = '中国民生银行';

    //         break;

    //     case 9:

    //         $info = '广东发展银行';

    //         break;

    //     default:

    //         $info = '';

    // }

    return $n;

}



/**

 * 配送方式

 *  

 * @param int $type 类型

 * @return string

 */

function get_shipping_type($type) {

    switch ($type) {

        case 1:

            $info = '快递';

            break;

        case 2:

            $info = 'EMS';

            break;

        case 3:

            $info = '平邮';

            break;

        case 4:

            $info = config('take_their_name')?config('take_their_name'):'服务中心';

            break;

        case 5:

            $info = '门店配送';

            break;

        default:

            $info = '快递';

    }

    return $info;

}



/*

 * 生成订单号

 *  

 * return string

 */

function get_orderno(){

    $order_no = date('Ymd').substr(time(), -5).substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 5);

    $order_id = M('Order')->where('order_no = "'.$order_no.'"')->getField('order_id');

    if($order_id){

        $order_no = get_orderno();

    }

    return $order_no;

}



/*

 * 生成扫码支付订单号

 *  

 * return string

 */

function get_code_orderno(){

    $order_no = 'S' . date('Ymd').substr(time(), -5).substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 5);

    $order_id = M('Order')->where('order_no = "'.$order_no.'"')->getField('order_id');

    if($order_id){

        $order_no = get_code_orderno();

    }

    return $order_no;

}



/**

 * 生成续费单号

 */

function getRenewOrder(){

    $order_no = 'R'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 11);

    $order_id = M('Renew')->where('trade_no = "'.$order_no.'"')->getField('renew_id');

    if($order_id){

        $order_no = getRenewOrder();

    }

    return $order_no;

}

/**

 * 赠送礼品订单号

 *  

 */

function get_prize_orderno(){

    $order_no = 'G'.date('mdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 11);

    $order_id = M('OrderPrize')->where('order_prize_no = "'.$order_no.'"')->getField('order_prize_id');

    if($order_id){

        return get_prize_orderno();

    }else{

        return $order_no;

    }

}

/**

 *积分兑换商品订单号

 */

function get_point_orderno(){

    $order_no = 'P'.date('mdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

    $order_id = M('PointExchangeOrder')->where('order_no = "'.$order_no.'"')->getField('point_exchange_order_id');

    if($order_id){

        $order_no = get_point_orderno();

    }

    return $order_no;

}

/**

 *试用商品商品订单号

 */

function get_try_orderno(){

    $order_no = 'T'.date('mdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

    $order_id = M('TryOrder')->where('order_no = "'.$order_no.'"')->getField('try_order_id');

    if($order_id){

        $order_no =  get_try_orderno();

    }

    return $order_no;

}

/**

 * 上传微信多媒体文件

 *  

 * @param $url

 * @param $file

 * @return mixed|string

 */

function uploadMedia($url, $file) {

    $fields['media'] = '@' . $file;

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $result = curl_exec($ch);

    if (curl_errno($ch)) {

        return curl_error($ch);

    }

    curl_close($ch);

    return $result;

}



/**

 *php实现下载远程图片到本地

 *@param $url       string      远程文件地址

 *@param $type      int         远程获取文件的方式

 * @param $user_id int          用户ＩＤ

 *@return           json        返回文件名、文件的保存路径

 */

function getImage($url,$user_id,$subffix='',$type=0)

{

    if($url == ''){return false;}

    //设置保存后的文件名

    $filename =  $subffix.$user_id.'.png';

    $shop_id = M('User')->where('user_id = '.$user_id)->getField('shop_id');

    //获取远程文件资源

    if($type){

        $ch = curl_init();

        $timeout = 5;

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

        $file = curl_exec($ch);

        curl_close($ch);

    }else{

        ob_start();

        readfile($url);

        $file = ob_get_contents();

        ob_end_clean();

    }

    //设置文件保存路径

    $dirName ='./Upload/'.substr(md5($shop_id),0,2).'/'.substr(md5($shop_id),2,2).'/'.$shop_id.'/'.substr(md5($user_id),0,2).'/'.substr(md5($user_id),2,2).'/'.$user_id.'/';

    if(!file_exists($dirName)){

        mkdir($dirName, 0755, true);

    }

    if(file_exists($dirName.$filename)){

        unlink($dirName.$filename);

    }

    if($file){

        //保存文件

        $res = fopen($dirName.$filename,'a');

        fwrite($res,$file);

        fclose($res);

    }

}





function getShopImage($url,$dir,$filename,$type=0){

    if($url == ''){return false;}

    //获取远程文件资源

    if($type){

        $ch = curl_init();

        $timeout = 5;

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

        $file = curl_exec($ch);

        curl_close($ch);

    }else{

        ob_start();

        readfile($url);

        $file = ob_get_contents();

        ob_end_clean();

    }

    //设置文件保存路径

    //$dirName = './Upload/card/'.$shop_id.'/';

    if(!file_exists($dir)){

        mkdir($dir, 0777, true);

    }

    if(file_exists($dir.$filename)){

        unlink($dir.$filename);

    }

    //保存文件

    $res = fopen($dir.$filename,'a');

    fwrite($res,$file);

    fclose($res);

}





function autowrap($fontsize,$angle,$fontface,$string,$width,&$px=0){

    // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度 

    $content = "";

    // 将字符串拆分成一个个单字 保存到数组 letter 中

    for ($i=0;$i<mb_strlen($string);$i++) {

        //$letter[] = mb_substr($string, $i, 1);

        $tter = trim(msubstr($string, $i, 1, "utf-8", false));

        if($tter || is_numeric($tter)){

            $letter[] = $tter;

        }

    }

    foreach ($letter as $l) {

        $teststr = $content." ".$l;

        $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);

        // 判断拼接后的字符串是否超过预设的宽度

        if (($testbox[2] > $width) && ($content !== "")) {

            $content .= "\n";

            $px++;

        }

        $content .= $l;

    }

    return $content;



}

/**

 * 生成分销名片

 *

 * @param string $out_file 输出文件路径和文件名（分销名片图片要保存的路径和文件名，服务器本地路径）

 * @param string $bg_path 背景图片路径和文件名（服务器本地路径）

 * @param string $qr_code_path 二维码图片路径（服务器本地路径）

 * @param integer $qr_code_x 二维码图片X坐标

 * @param integer $qr_code_y 二维码图片Y坐标

 * @param integer $qr_code_w 二维码显示宽度

 * @param integer $qr_code_h 二维码高度

 * @param string $icon_url 微信头像图片网址（网址为微信的网址）

 * @param integer $icon_shade 4e381a 微信头像图片外形，1为正方形，2为圆形（微信提供的都是正方形，但我们有的模板中要显示圆形，所以要根据此值来决定是否将图片改为圆形）

 * @param integer $icon_x 微信头像图片X坐标

 * @param integer $icon_y 微信头像图片Y坐标

 * @param integer $icon_w 微信头像宽度

 * @param integer $icon_h 微信头像高度

 * @param string $my_name 昵称内容，如：“我是XXX”

 * @param integer $my_name_x 昵称显示位置的X坐标

 * @param integer $my_name_y 昵称显示位置的Y坐标

 * @param string $text_font 昵称字体，使用本地服务器路径（字体放在\Public\font\目录下）

 * @param integer $text_size 昵称字号

 * @param string $text_color 昵称文字颜色

 * @return void

 */

function create_fenxiao_card($out_file,

                             $bg_path,

                             $qr_code_path,

                             $qr_code_x,

                             $qr_code_y,

                             $qr_code_w,

                             $qr_code_h,

                             $icon_url,

                             $icon_type,

                             $icon_x,

                             $icon_y,

                             $icon_w,

                             $icon_h,

                             $my_name,

                             $my_name_x,

                             $my_name_y,

                             $text_font,

                             $text_size,

                             $text_color,$card_type="fx_card",$is_icon_my=1)

{

    $icon_shade = './Public/images/mask_pic/' . $icon_type . '.png';

    $text_font = APP_PUBLIC.'font/'.$text_font;

    //先判断背景图片的类型

    if(!$bg_path){

        exit('bg_path is null!');

    }

    $bg_data  =  getimagesize($bg_path);

    switch($bg_data[2])

    {

        case  1:

            $im_bg = @imagecreatefromgif($bg_path);

            $im_bg_bak = @imagecreatefromgif($bg_path);

            break;

        case  2:

            $im_bg = @imagecreatefromjpeg($bg_path);

            $im_bg_bak = @imagecreatefromjpeg($bg_path);

            break;

        default:

            $im_bg = @imagecreatefrompng($bg_path);

            $im_bg_bak = @imagecreatefrompng($bg_path);

            break;

    }

    // file_put_contents('tpl.txt',config('card_tpl_id'));

    if($is_icon_my ==1){

        $is_icon_my = config('card_tpl_id');

    }

    if($is_icon_my ==1){

        $my_name = emoji_filter($my_name);

        $homepage_tpl_id = config('card_tpl_id');

        if($homepage_tpl_id == 10 && $card_type != 'user_card'){

            $my_name = autowrap($text_size, 0, $text_font, $my_name, 20,$px); // 自动换行处理

        }

        if($text_font !=1){

            //添加昵称

            imagettftext ( $im_bg,  $text_size,  0, $my_name_x,  $my_name_y,  $text_color,  $text_font,  $my_name);

        }



        if($icon_url != 1){

            //获取logo图片的类型

            $logo_data  =  getimagesize($icon_url);



            switch($logo_data[2])

            {

                case  1:

                    $im_logo = @imagecreatefromgif($icon_url);

                    break;

                case  2:

                    $im_logo = @imagecreatefromjpeg($icon_url);

                    break;

                default:

                    $im_logo = @imagecreatefrompng($icon_url);

                    break;

            }



            //压缩LOGO

            if($icon_w < $logo_data[0] || $logo_data[1] > $icon_h){



                //改变后的图象的比例

                $resize_ratio = ($icon_w)/($icon_h);



                $newlogo = imagecreatetruecolor($icon_w, $icon_h);

                imagecopyresized($newlogo, $im_logo, 0, 0, 0, 0, $icon_w,$icon_h, (($logo_data[0])*$resize_ratio), $logo_data[1]);



                //处理logo边缘$icon_shade

                $im_shade = @imagecreatefrompng($icon_shade);

                $shade_data  =  getimagesize($icon_shade);



                //压缩遮罩

                $newshade = imagecreatetruecolor($icon_w, $icon_h);

                $bg = imagecolorallocatealpha($newshade, 0, 0, 0, 127);

                imagealphablending($newshade,false);

                imagefill($newshade,0,0,$bg);

                imagesavealpha($newshade,true);



                imagecopyresized($newshade, $im_shade, 0, 0, 0, 0, $icon_w,$icon_h, (($shade_data[0])*$resize_ratio), $shade_data[1]);



                imagecopy($im_bg, $newshade, $icon_x, $icon_y, 0, 0, $icon_w, $icon_h);

                imagecolortransparent  ($im_bg , imagecolorallocate ( $im_bg ,  0x4e ,  0x38 ,  0x1a ));



                imagecopy($im_bg_bak, $newlogo, $icon_x, $icon_y, 0, 0, $icon_w, $icon_h);



                imagecopymerge($im_bg_bak, $im_bg, 0, 0, 0, 0, $bg_data[0], $bg_data[1], 100);



                imagecopy($im_bg, $im_bg_bak, 0, 0, 0, 0, $bg_data[0], $bg_data[1]);



                @ImageDestroy($im_bg_bak);

                @ImageDestroy($newshade);

                @ImageDestroy($im_shade);

            }else{

                //处理logo边缘$icon_shade

                $im_shade = @imagecreatefrompng($icon_shade);

                $shade_data  =  getimagesize($icon_shade);



                imagecopy($im_bg, $im_shade, $icon_x, $icon_y, 0, 0, $logo_data[0], $logo_data[1]);

                imagecolortransparent  ($im_bg , imagecolorallocate ( $im_bg ,  0x4e ,  0x38 ,  0x1a ));



                imagecopy($im_bg_bak, $im_logo, $icon_x, $icon_y, 0, 0, $logo_data[0], $logo_data[1]);



                imagecopymerge($im_bg_bak, $im_bg, 0, 0, 0, 0, $bg_data[0], $bg_data[1], 100);



                imagecopy($im_bg, $im_bg_bak, 0, 0, 0, 0, $bg_data[0], $bg_data[1]);



                @ImageDestroy($im_bg_bak);

                @ImageDestroy($im_shade);

            }



            @ImageDestroy($im_logo);

        }

    }

    //获取二维码图片的类型

    $qr_data  =  getimagesize($qr_code_path);



    switch($qr_data[2])

    {

        case  1:

            $im_qr = @imagecreatefromgif($qr_code_path);

            break;

        case  2:

            $im_qr = @imagecreatefromjpeg($qr_code_path);

            break;

        default:

            $im_qr = @imagecreatefrompng($qr_code_path);

            break;

    }

    $expires_d = date('Y-m-d',time()+2592000);

    //添加二维码有效期

    // imagettftext ($im_bg, 20, 0, 148, 0, $text_color, $text_font, "1此二维码有效推广期截止asdjhasuiodasiouhdjasdkjahdkajs11111eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeqwi45165sad4f65a4sd654as65d465wq4e65qw4e65q4w2e64qwe5665qw4e56w4e6qw45e5q为：$expires_d"); 

    // imagettftext ($im_bg, 14, 0, 80, 10, $text_color, $text_font, "此二维码有效推广期截止为：$expires_d"); 

    imagettftext ($im_bg, 15, 0, 140, 880, '0xff0000', $text_font, "此二维码有效推广期截止为：$expires_d");

    // file_put_contents('font1',$text_color);

    // file_put_contents('font.txt',$text_font);

    //压缩二维码

    // $qr_data[0] =+10;$qr_data[1] =+10;



    if($qr_code_w< $qr_data[0] || $qr_data[1] > $qr_code_h){

        // file_put_contents('1234',"      $qr_code_w< $qr_data[0] || $qr_data[1] > $qr_code_h                     ");

        //改变后的图象的比例

        $resize_ratio = ($qr_code_w)/($qr_code_h);



        $newewm = imagecreatetruecolor($qr_code_w+35, $qr_code_h+35);

        // imagecopyresampled($newewm, $im_qr, 0, 0, 0, 0, $qr_code_w,$qr_code_h, (($qr_data[0])*$resize_ratio), $qr_data[1]);

        imagecopyresampled($newewm, $im_qr, 0, 0, 0, 0, $qr_code_w,$qr_code_h, $qr_data[0], $qr_data[1]);



        imagecopymerge($im_bg, $newewm, $qr_code_x-70, $qr_code_y-140, 0, 0, $qr_code_w, $qr_code_h, 100);



    }else{

        // file_put_contents('321',"      $qr_code_w< $qr_data[0] || $qr_data[1] > $qr_code_h                     ");

        imagecopymerge($im_bg, $im_qr, $qr_code_x, $qr_code_y, 0, 0, $qr_data[0], $qr_data[1], 100);

    } 



    @ImageDestroy($im_qr);



    //生成图片

    //header("content-type:image/png");

    //imagejpeg ( $im_bg);

    imagejpeg ( $im_bg ,  $out_file);

    imagedestroy ( $im_bg );

}





/**

 * 生成分销商名片上传到本地

 *  

 */

function upload_location_card($user_id,$qrcode_url,$img='card'){

    $shop_id = M('User')->where('user_id = '.$user_id)->getField('shop_id');

    if($img == 'usercard'){

        $homepage_tpl_id = config('user_card_tpl_id', null,$shop_id);

        $homepage_tpl_id = $homepage_tpl_id ? $homepage_tpl_id :3;

        $info = M('UsercardTpl')->where('usercard_tpl_id = '.$homepage_tpl_id)->find();

        $current = M('ShopUsercardTpl')->where('shop_id = '.$shop_id.' AND usercard_tpl_id = '.$homepage_tpl_id)->find();

        if(!empty($current)){

            $info = $current;

            $info['img_url'] = '.'.$current['img_url'];

            $info['bg_path'] = '.'.$current['bg_path'];

        }else{

            $info['img_url'] = '.'.$info['img_url'];

            $info['bg_path'] = '.'.$info['bg_path'];

        }

        $card_type = 'user_card';

    }else{

        $homepage_tpl_id = config('card_tpl_id', null, $shop_id);

        $homepage_tpl_id = $homepage_tpl_id ? $homepage_tpl_id : C('HOMEPAGE_TPL_ID');

        $info = M('CardTpl')->where('card_tpl_id = '.$homepage_tpl_id)->find();

        $current = M('ShopCardTpl')->where('shop_id = '.$shop_id.' AND card_tpl_id = '.$homepage_tpl_id)->find();

        if(!empty($current)){

            $info = $current;

            $info['img_url'] = '.'.$current['img_url'];

            $info['bg_path'] = '.'.$current['bg_path'];

        }else{

            $info['img_url'] = '.'.$info['img_url'];

            $info['bg_path'] = '.'.$info['bg_path'];

        }

        $card_type = 'fx_card';

    }



    $dirName ='./Upload/'.substr(md5($shop_id),0,2).'/'.substr(md5($shop_id),2,2).'/'.$shop_id.'/'.substr(md5($user_id),0,2).'/'.substr(md5($user_id),2,2).'/'.$user_id.'/';

    $out_file = $dirName.$img.$user_id.'.jpg';

    if($info['text_font'] !=1){

        $nickname = D('Home/User')->getNick($user_id);

        if(abslength($nickname)>8){

            $info['text_size'] = 16;

        }

    }

    if($info['icon_url'] !=1){

        $author = D('Home/User')->getDfHeadImg($user_id);

        if($author){

            getImage($author, $user_id,'author',1);

            $author = $dirName.'author'.$user_id.'.png';

        }

    }else{

        $author = 1;

    }

    $y= config('card_tpl_id');

    if($y==1){

        $y=2;

    }else{

        $y=1;

    }

    create_fenxiao_card($out_file, $info['bg_path'], $qrcode_url,

        $info['qr_code_x'],

        $info['qr_code_y'],

        $info['qr_code_w']+150, $info['qr_code_h']+150, $author, $info['icon_type'], $info['icon_x'], $info['icon_y'], $info['icon_w'], $info['icon_h'], $nickname, $info['my_name_x'], $info['my_name_y'], $info['text_font'], $info['text_size'], $info['text_color'],$card_type,$y);

    // file_put_contents('card',$out_file);

}



/**

 * 生成代理商名片上传到本地

 *  

 */

function upload_location_dlcard($user_id,$qrcode_url){

    $rank = M('UserDls')->where('user_id = '.$user_id.' AND is_dls = 1')->getField('rank');

    if(!$rank){

       return false;

    }

    $ftitle_agencies = config('ftitle_agencies');

    $ftitle_agencies = is_null($ftitle_agencies) ? '代理商' : $ftitle_agencies;

    if($rank == 1){

        $dls = '一级'.$ftitle_agencies;

    }elseif($rank == 2){

        $dls = '二级'.$ftitle_agencies;

    }elseif($rank == 3){

        $dls = '三级'.$ftitle_agencies;

    }else{

        return false;

    }

    $user_info = M('User')->where('user_id = '.$user_id)->field('shop_id,weixin_account')->find();

    $shop_id = $user_info['shop_id'];

    $homepage_tpl_id = config('dl_card_tpl_id', null, $shop_id);

    $homepage_tpl_id = $homepage_tpl_id ? $homepage_tpl_id : C('HOMEPAGE_TPL_ID');

    $info = M('DlcardTpl')->where('dlcard_tpl_id = '.$homepage_tpl_id)->find();

    $current = M('ShopDlcardTpl')->where('shop_id = '.$shop_id.' AND dlcard_tpl_id = '.$homepage_tpl_id)->find();

    if(!empty($current)){

        $info['img_url'] = '.'.$current['img_url'];

        $info['bg_path'] = '.'.$current['bg_path'];

    }else{

        $info['img_url'] = '.'.$info['img_url'];

        $info['bg_path'] = '.'.$info['bg_path'];

    }

    $nickname = D('Home/User')->getNick($user_id);

    if(abslength($nickname)>8){

        $info['text_size'] = 16;

    }

    $dirName ='./Upload/'.substr(md5($shop_id),0,2).'/'.substr(md5($shop_id),2,2).'/'.$shop_id.'/'.substr(md5($user_id),0,2).'/'.substr(md5($user_id),2,2).'/'.$user_id.'/';

    $out_file = $dirName.'dlcard'.$user_id.'.jpg';

    $shop_title = M('Shop')->where('shop_id = '.$shop_id)->getField('title');

    create_dls_card($out_file, $info['bg_path'], $qrcode_url,

        $info['qr_code_x'],

        $info['qr_code_y'],

        $info['qr_code_w'], $info['qr_code_h'], $user_info['weixin_account'],$info['icon_x'], $info['icon_y'],$nickname, $info['my_name_x'], $info['my_name_y'],

        $dls,$info['dls_x'], $info['dls_y'],$shop_title, $info['shop_name_x'], $info['shop_name_y'],

        $info['text_font'], $info['text_size'], $info['text_color'],$info['shop_name_size']);



}



/**

 * 生成分销名片

 *

 * @param string $out_file 输出文件路径和文件名（分销名片图片要保存的路径和文件名，服务器本地路径）

 * @param string $bg_path 背景图片路径和文件名（服务器本地路径）

 * @param string $qr_code_path 二维码图片路径（服务器本地路径）

 * @param integer $qr_code_x 二维码图片X坐标

 * @param integer $qr_code_y 二维码图片Y坐标

 * @param integer $qr_code_w 二维码显示宽度

 * @param integer $qr_code_h 二维码高度

 * @param string $icon_url 微信头像图片网址（网址为微信的网址）

 * @param integer $icon_shade 4e381a 微信头像图片外形，1为正方形，2为圆形（微信提供的都是正方形，但我们有的模板中要显示圆形，所以要根据此值来决定是否将图片改为圆形）

 * @param integer $icon_x 微信头像图片X坐标

 * @param integer $icon_y 微信头像图片Y坐标

 * @param integer $icon_w 微信头像宽度

 * @param integer $icon_h 微信头像高度

 * @param string $my_name 昵称内容，如：“我是XXX”

 * @param integer $my_name_x 昵称显示位置的X坐标

 * @param integer $my_name_y 昵称显示位置的Y坐标

 * @param string $text_font 昵称字体，使用本地服务器路径（字体放在\Public\font\目录下）

 * @param integer $text_size 昵称字号

 * @param string $text_color 昵称文字颜色

 * @return void

 */

function create_dls_card($out_file,

                             $bg_path,

                             $qr_code_path,

                             $qr_code_x,

                             $qr_code_y,

                             $qr_code_w,

                             $qr_code_h,

                             $icon,

                             $icon_x,

                             $icon_y,

                             $my_name,

                             $my_name_x,

                             $my_name_y,

                             $dls,

                             $dls_x,

                             $dls_y,

                             $shop_name,

                             $shop_name_x,

                             $shop_name_y,

                             $text_font,

                             $text_size,

                             $text_color,$shop_name_size)

{

    //$icon_shade = './Public/images/mask_pic/' . $icon_type . '.png';

    $text_font = APP_PUBLIC.'font/'.$text_font;

    //先判断背景图片的类型

    if(!$bg_path){

        exit('bg_path is null!');

    }

    $bg_data  =  getimagesize($bg_path);

    switch($bg_data[2])

    {

        case  1:

            $im_bg = @imagecreatefromgif($bg_path);

            $im_bg_bak = @imagecreatefromgif($bg_path);

            break;

        case  2:

            $im_bg = @imagecreatefromjpeg($bg_path);

            $im_bg_bak = @imagecreatefromjpeg($bg_path);

            break;

        default:

            $im_bg = @imagecreatefrompng($bg_path);

            $im_bg_bak = @imagecreatefrompng($bg_path);

            break;

    }



    //添加昵称

    imagettftext ( $im_bg,  $text_size,  0, $my_name_x,  $my_name_y,  $text_color,  $text_font,  $my_name);

    //添加代理商等级

    imagettftext ( $im_bg,  $text_size,  0, $dls_x,  $dls_y,  $text_color,  $text_font,  $dls);

    //添加店铺名称

    imagettftext ( $im_bg,  $shop_name_size,  0, $shop_name_x,  $shop_name_y,  $text_color,  $text_font,  $shop_name);

    //添加微信号

    imagettftext ( $im_bg,  $text_size,  0, $icon_x,  $icon_y,  $text_color,  $text_font,  $icon);

    //添加二维码有效期

    imagettftext ($im_bg, 14, 0, 148, 740, $text_color, $text_font, "此二维码有效推广期截止为：$expires_d");  

    //获取二维码图片的类型

    $qr_data  =  getimagesize($qr_code_path);



    switch($qr_data[2])

    {

        case  1:

            $im_qr = @imagecreatefromgif($qr_code_path);

            break;

        case  2:

            $im_qr = @imagecreatefromjpeg($qr_code_path);

            break;

        default:

            $im_qr = @imagecreatefrompng($qr_code_path);

            break;

    }





    //压缩二维码

    if($qr_code_w < $qr_data[0] || $qr_data[1] > $qr_code_h){



        //改变后的图象的比例

        $resize_ratio = ($qr_code_w)/($qr_code_h);



        $newewm = imagecreatetruecolor($qr_code_w, $qr_code_h);

        imagecopyresampled($newewm, $im_qr, 0, 0, 0, 0, $qr_code_w,$qr_code_h, (($qr_data[0])*$resize_ratio), $qr_data[1]);



        imagecopymerge($im_bg, $newewm, $qr_code_x, $qr_code_y, 0, 0, $qr_code_w, $qr_code_h, 100);



    }else{

        imagecopymerge($im_bg, $im_qr, $qr_code_x, $qr_code_y, 0, 0, $qr_data[0], $qr_data[1], 100);

    }



    @ImageDestroy($im_qr);



    //生成图片

    //header("content-type:image/png");

    //imagejpeg ( $im_bg);

    imagejpeg ( $im_bg ,  $out_file);

    imagedestroy ( $im_bg );

}

/**

 * 可以统计中文字符串长度的函数

 * @param $str 要计算长度的字符串

 * @param $type 计算长度类型，0(默认)表示一个中文算一个字符，1表示一个中文算两个字符

 *

 */

function abslength($str){

    if(empty($str)){

        return 0;

    }

    if(function_exists('mb_strlen')){

        return mb_strlen($str,'utf-8');

    }else{

        preg_match_all("/./u", $str, $ar);

        return count($ar[0]);

    }



}



/**

 * 获取二维码的参数

 *  

 */

function getQrcodeId($user_id){

    $shop_id = M('User')->where('user_id = '.$user_id)->getField('shop_id');

    $map = array(

        'user_id'=>$user_id,

        'shop_id' =>$shop_id,

    );

    $scene_id = M('User')->where($map)->getField('scene_id');

    if(!$scene_id){

        $max_scene_id = M('User')->db(1, 'MASTER_DB')->where('shop_id = '.$shop_id)->max('scene_id');

        if($max_scene_id <100000){

            $scene_id = $max_scene_id +1;

            M('User')->where($map)->setField('scene_id',$scene_id);

        }else{

            M()->startTrans();

            $sql = 'select scene_id,user_id from (select scene_id,user_id from tp_user where shop_id = '.$shop_id.' AND scene_id >0 AND is_user_del != 0 limit 1) t where  not exists (select 1 from tp_user_dls where shop_id = '.$shop_id.' AND user_id=t.user_id AND is_dls = 1) for update';

            $info = M()->query($sql);

            if(!empty($info)){

                $scene_id =  $info[0]['scene_id'];

                M('User')->where('user_id = '.$info[0]['user_id'],' AND shop_id = '.$shop_id)->save(array('media_create_time'=>null,'scene_id'=>null));

                M('User')->where($map)->setField('scene_id',$scene_id);

                M()->commit();

                $dirName ='./Upload/'.substr(md5($shop_id),0,2).'/'.substr(md5($shop_id),2,2).'/'.$shop_id.'/'.substr(md5($info[0]['user_id']),0,2).'/'.substr(md5($info[0]['user_id']),2,2).'/'.$info[0]['user_id'];

                $filename =$dirName. '/'.$info[0]['user_id'].'.png';

                unlink($filename);

            }else{

                $scene_id =  $max_scene_id +1;

                M('User')->where($map)->setField('scene_id',$scene_id);

                M()->commit();

            }

        }

    }

    return intval($scene_id);

}



/**

 * 发送站内信

 *  

 */

function sendLetter($user_id,$content,$type=9){

    $shop_id = M('User')->where('user_id = '.$user_id)->getField('shop_id');

    $data = array(

        'shop_id'=>$shop_id,

        'type'=>$type,

        'content'=>$content,

        'create_time'=>NOW_TIME,

        'send_time'=>NOW_TIME,

        'status'=>0,

    );

    $id = M('Message')->add($data);

    if($id){

        $UserMessage = M('UserMessage');

        $unread_id = $UserMessage->where('user_id = ' . $user_id)->getField('unread_id');

        if ($unread_id === null) {

            $MessageUser = M('MessageUser');

            $unread = $MessageUser->where(array('user_id'=>$user_id, 'status'=>0))->getField('message_id', true);

            $read = $MessageUser->where(array('user_id'=>$user_id, 'status'=>1))->getField('message_id', true);

            if ($unread || $read) {

                $read_id = $unread_id = '';

                if ($unread) {

                    $unread_id = implode(',', $unread);

                    $unread_id .= ',' . $id;

                }

                if ($read) {

                    $read_id = implode(',', $read);

                }

                $data = array('user_id' => $user_id, 'unread_id' => $unread_id, 'read_id' => $read_id, 'last_time' => NOW_TIME, 'dc_shop'=>$shop_id);

            } else {

                $data = array('user_id' => $user_id, 'unread_id' => $id, 'last_time' => NOW_TIME, 'dc_shop'=>$shop_id);

            }

            $res = $UserMessage->add($data);

        } else {

            if ($unread_id) $unread_id .= ',' . $id;

            else $unread_id = $id;

            $data = array('user_id'=>$user_id, 'unread_id'=>$unread_id);

            $res = $UserMessage->save($data);

        }



        if($res){

            M('Message')->where('message_id = '.$id)->save(array('status'=>1));

        }

    }



    return $res;

}



/**

 * 获取快递单号

 *  

 */

function expressTracking($express_name,$express_no){

    Vendor('Kd100.Express#class');

    $express = new \Express();

    $result  = $express -> newGetOrder($express_name,$express_no);

    return $result;

}



/**

 * 内容格式化

 *  

 */

function content_format($content) {

    $content = htmlspecialchars_decode($content);

    $content = preg_replace('/<p[^>]*>/isU', '', $content);

    $content = str_replace('</p>', "\n", $content);

    $content = str_replace('&nbsp;', ' ', $content);

    $content = preg_replace('/<a href="([^>]*)"[^>]*>/isU', '<a href="$1">', $content);

    $content = preg_replace('/<span[^>]*>/isU', '', $content);

    $content = str_replace('</span>', '', $content);

    $content = preg_replace('/<strong[^>]*>/isU', '', $content);

    $content = str_replace('</strong>', '', $content);

    $content = preg_replace('/<ol[^>]*>/isU', '', $content);

    $content = str_replace('</ol>', '', $content);

    $content = str_replace('<li>', '', $content);

    $content = str_replace('</li>', '', $content);

    $arr_content = explode('<br/>', $content);

    $content = implode("\n", $arr_content);

    $content = rtrim($content, "\n");

    return $content;

}



function send_msg_content($content,$nickname,$shop_title,$count,$sup_nickname=null,$user_id=null){

    $content =  str_replace('{插入昵称}',$nickname,$content);

    $content =   str_replace('{插入店铺}',$shop_title,$content);

    $content =   str_replace('{插入会员个数}',$count,$content);

    $content =   str_replace('{插入上级昵称}',$sup_nickname,$content);

    $content =   str_replace('{插入ID号}',$user_id,$content);

    $content = addslashes(content_format($content));

    return $content;

}



function update_gent_content($content,$shop_title,$agent_level,$bonus_level=null){

    $content =   str_replace('{插入店铺}',$shop_title,$content);

    $content =   str_replace('{插入分销商等级}',$agent_level,$content);

    $content =   str_replace('{插入分红等级}',$bonus_level,$content);

    $content = addslashes(content_format($content));

    return $content;

}



function fx_card_content($content,$link=null,$nickname=null,$title=null,$order_no=null,$express_no=null,$compay_express=null,$remark = null){

    if($link){

        $content =  str_replace('{插入链接}',$link,$content);

    }

    if($nickname){

        $content =  str_replace('{插入昵称}',$nickname,$content);

    }

    if($title){

        $content =  str_replace('{插入商品标题}',$title,$content);

    }

    if($order_no){

        $content =  str_replace('{插入订单号}',$order_no,$content);

    }

    if($express_no){

        $content =  str_replace('{插入快递单号}',$express_no,$content);

    }

    if($compay_express){

        $content =  str_replace('{插入快递公司}',$compay_express,$content);

    }

    if($remark){

        $content =  str_replace('{插入理由}',$remark,$content);

    }

    $content = content_format($content);



    return $content;

}



function order_send_content($content,$link=null,$nickname=null,$title=null,$order_no=null,$express_no=null,$compay_express=null,$remark = null){

    $content =  str_replace('{插入链接}',$link,$content);

    $content =  str_replace('{插入昵称}',$nickname,$content);

    $content =  str_replace('{插入商品标题}',$title,$content);

    $content =  str_replace('{插入订单号}',$order_no,$content);

    $content =  str_replace('{插入快递单号}',$express_no,$content);

    $content =  str_replace('{插入快递公司}',$compay_express,$content);

    $content =  str_replace('{插入理由}',$remark,$content);

    $content = addslashes(content_format($content));



    return $content;

}



function apply_agent_content($content,$link=null,$nickname=null,$agent_level=null){

        $content =  str_replace('{插入链接}',$link,$content);

        $content =  str_replace('{插入昵称}',$nickname,$content);

        $content =  str_replace('{插入分销商等级}',$agent_level,$content);

        $content = addslashes(content_format($content));

         return $content;

}



/**

 * 支付宝配置参数

 * @param order_id 订单ＩＤ

 *  

 */

function alipayConfig($shop_id=SHOP_ID){

    $where = array('shop_id'=>$shop_id,'status'=>1);

    $alipay_info = array(

        'sign_type'=>strtoupper('MD5'),

        'input_charset'=> strtolower('utf-8'),

        'cacert'=> getcwd().'\\cacert.pem',

        'transport'=> 'http',



    );

    $info =  D('Shop')->where($where)->field('alipay_account,alipay_partner,alipay_key,alipay_name')->find();

    if($info['alipay_partner'] && $info['alipay_key'] && $info['alipay_account']){

        $alipay_info['seller_email'] = $info['alipay_account'];

        $alipay_info['partner'] = $info['alipay_partner'];

        $alipay_info['key'] = $info['alipay_key'];

        $alipay_info['alipay_name'] = $info['alipay_name'];

    }

    return $alipay_info;

}



/**

 * APP发送

 * @param int $sendno 发送编号。由开发者自己维护，标识一次发送请求

 * @param int $receiver_type 接收者类型。

 *                           1、指定的 IMEI。此时必须指定 appKeys。

 *                           2、指定的 tag。

 *                           3、指定的 alias。

 *                           4、 对指定 appkey 的所有用户推送消息。

 * @param string $receiver_value 发送范围值，与 receiver_type相对应。

 *                               1、IMEI只支持一个

 *                               2、tag 支持多个，使用 "," 间隔。

 *                               3、alias 支持多个，使用 "," 间隔。

 *                               4、不需要填

 * @param int $msg_type 发送消息的类型：

 *                      1、通知

 *                      2、自定义消息

 * @param string $msg_content 发送消息的内容。 与 msg_type 相对应的值

 * @param string $platform 目标用户终端手机的平台类型，如： android, ios 多个请使用逗号分隔

 */

function app_send($sendno = 15,$receiver_type = 1, $receiver_value = "", $msg_type = 1, $msg_content = "", $platform = 'android'){

    $_appkeys = 'f56202b0bf186fd3ce8d1367';

    $_masterSecret = 'a93a511b10db22df41085b3b';

    $url = 'http://api.jpush.cn:8800/sendmsg/v2/sendmsg';

    $param = '';

    $param .= '&sendno='.$sendno;

    $param .= '&app_key='.$_appkeys;

    $param .= '&receiver_type='.$receiver_type;

    $param .= '&receiver_value='.$receiver_value;

    $masterSecret = $_masterSecret;

    $verification_code = md5($sendno.$receiver_type.$receiver_value.$masterSecret);

    $param .= '&verification_code='.$verification_code;

    $param .= '&msg_type='.$msg_type;

    $param .= '&msg_content='.$msg_content;

    $param .= '&platform='.$platform;

    $ch = curl_init();//初始化curl

    curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页

    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上

    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式

    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

    $data = curl_exec($ch);//运行curl

    curl_close($ch);

    $res_arr = json_decode($data, true);



    return $res_arr;

}



/**

 * 加密函数

 *  

 */

function encrypt($data, $key='wfx') {

    $prep_code = serialize($data);

    $block = mcrypt_get_block_size('des', 'ecb');

    if (($pad = $block - (strlen($prep_code) % $block)) < $block) {

        $prep_code .= str_repeat(chr($pad), $pad);

    }

    $encrypt = mcrypt_encrypt(MCRYPT_DES, $key, $prep_code, MCRYPT_MODE_ECB);

    return base64_encode($encrypt);

}



/**

 * 解密函数

 *  

 */

function decrypt($str, $key='wfx') {

    if (!$str) return '';

    $str = base64_decode($str);

    $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);

    $block = mcrypt_get_block_size('des', 'ecb');

    $pad = ord($str[($len = strlen($str)) - 1]);

    if ($pad && $pad < $block && preg_match('/' . chr($pad) . '{' . $pad . '}$/', $str)) {

        $str = substr($str, 0, strlen($str) - $pad);

    }

    $res = unserialize($str);

    if (defined('VERSION_NAME') && (strpos(VERSION_NAME, '演示版') !== false) && is_mobile($res)) $res = star_mobile($res);

    return $res;

}



/**

 * XSS过滤

 *  

 */

function xss_filter($content){

    $content = preg_replace("/<script[^>]*?>.*?<\/script>/si",'',$content);

    $content = preg_replace("/&lt;script[^(&gt;)]*?&gt;.*?&lt;\/script&gt;/si",'',$content);

    $content = preg_replace("/<img[^>]*?onerror[^>]*?>/si",'',$content);

    $content = preg_replace("/&lt;img[^(&gt;)]*?onerror[^(&gt;)]*?&gt;/si",'',$content);

    $content = preg_replace("/<input[^>]*?on[^>]*?>/si",'',$content);

    $content = preg_replace("/&lt;input[^(&gt;)]*?on[^(&gt;)]*?&gt;/si",'',$content);

    $find = array(

        '<script',

        'fromCharCode',

        '<prompt',

        'onerror',

        'alert',

    );

    $replace = array(

        '<ｓcript',

        'ｆromCharCode',

        '<ｐrompt',

        'ｏnerror',

        'ａlert',

    );

    $content = str_ireplace($find, $replace, $content);

    return $content;

}



/**

 * 是否开启发送消息配置

 *  

 * @return array

 */

function send_message_config($type,$shop_id = SHOP_ID){

    $return = array();

    $return['is_message_send'] = is_null(config('is_message_send'.$type,null,$shop_id))?C('IS_MESSAGE_SEND'):config('is_message_send'.$type,null,$shop_id);

    $return['is_message_app_send'] = is_null(config('is_message_app_send'.$type,null,$shop_id))?C('IS_MESSAGE_APP_SEND'):config('is_message_app_send'.$type,null,$shop_id);

    $return['is_message_sms_send'] = is_null(config('is_message_sms_send'.$type,null,$shop_id))?C('IS_MESSAGE_SMS_SEND'):config('is_message_sms_send'.$type,null,$shop_id);

    $return['is_message_letter_send'] = is_null(config('is_message_letter_send'.$type,null,$shop_id))?C('IS_MESSAGE_LETTER_SEND'):config('is_message_letter_send'.$type,null,$shop_id);

    $return['is_sms_send_seller'] = is_null(config('is_sms_send_seller'.$type,null,$shop_id))?C('IS_MESSAGE_LETTER_SEND'):config('is_sms_send_seller'.$type,null,$shop_id);

    return $return ;

}



/**

 * 检验是否有剩余短信

 *  

 */

function check_sms_num($shop_id = SHOP_ID){

    $sms_num = M('Shop')->where('shop_id = '.$shop_id)->getField('sms_num');

    if($sms_num >0){

        return true;

    }

    return false;

}



function order_msg_content($content,$nickname=null,$shop_title=null,$commission=null,$order_no=null,$remark=null){

    $content =  str_replace('{插入昵称}',$nickname,$content);

    $content =  str_replace('{插入店铺}',$shop_title,$content);

    $content =  str_replace('{插入佣金}',$commission,$content);

    $content =  str_replace('{插入订单号}',$order_no,$content);

    $content =  str_replace('{插入理由}',$remark,$content);

    $content = addslashes(content_format($content));



    return $content;

}

function apply_agent_msg($content,$shop_title){

    $content =  str_replace('{插入店铺}',$shop_title,$content);

    $content = addslashes(content_format($content));

    return $content;

}

function send_coupon_content($content,$shop_title,$coupon_value){

    $content =  str_replace('{插入店铺}',$shop_title,$content);

    $content =  str_replace('{插入优惠券面值}',$coupon_value,$content);

    $content = addslashes(content_format($content));

    return $content;

}

function send_coupon_pack_content($content,$shop_title,$coupon_value){

    $content =  str_replace('{插入店铺}',$shop_title,$content);

    $content =  str_replace('{插入大礼包面值}',$coupon_value,$content);

    $content = addslashes(content_format($content));

    return $content;

}



function p ($array) {

    dump($array, 1, '<pre>', 0);

}



/**

 * 过滤emoji

 *  

 */

function emoji_filter($nick) {

    $nick = json_encode($nick);

    $nick = preg_replace('/\\\u[e|d|0][0-9a-f]{3}/ie', '', $nick);

    $nick = json_decode($nick);

    return $nick;

}



/**

 * 获取手机号归属地

 *  

 */

function get_mobile_info($mobile) {

    $url = 'http://virtual.paipai.com/extinfo/GetMobileProductInfo?mobile=' . $mobile . '&amount=10000&callname=getPhoneNumInfoExtCallback';

    $content = iconv('gbk', 'utf-8', curl($url));

    preg_match('/province:\'(.*)\'.*cityname:\'(.*)\'/U', $content, $match);

    if ($match[1] || $match[2]) return $match[1] . $match[2];

    else return false;

}







function create_noncestr( $length = 16 ) {

    $chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";

    $str ="";

    for ( $i = 0; $i < $length; $i++ )  {

        $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);

    }

    return $str;

}



function setLevelCount($superior_id,$top_id,$three_id,$shop_id = SHOP_ID,$count=1){

    $User = M('User');

    if($superior_id){

        if(checkShopUser($superior_id,$shop_id)){

            $User->where('user_id = '.$superior_id)->setInc('superior_level',$count);

            $User->where('user_id = '.$superior_id)->setInc('total_level',$count);

        }

    }

    if($top_id){

        if(checkShopUser($top_id,$shop_id)){

            $User->where('user_id = '.$top_id)->setInc('top_level',$count);

            $User->where('user_id = '.$top_id)->setInc('total_level',$count);

        }

    }

    if($three_id){

        if(checkShopUser($three_id,$shop_id)){

            $User->where('user_id = '.$three_id)->setInc('three_level',$count);

            $User->where('user_id = '.$three_id)->setInc('total_level',$count);

        }

    }

}

function reduceLevelCount($superior_id,$top_id,$three_id,$shop_id = SHOP_ID,$count=1){

    $User = M('User');

    if($superior_id){

        if(checkShopUser($superior_id,$shop_id)){

            $User->where('user_id = '.$superior_id)->setDec('superior_level',$count);

            $User->where('user_id = '.$superior_id)->setDec('total_level',$count);

        }

    }

    if($top_id){

        if(checkShopUser($top_id,$shop_id)){

            $User->where('user_id = '.$top_id)->setDec('top_level',$count);

            $User->where('user_id = '.$top_id)->setDec('total_level',$count);

        }

    }

    if($three_id){

        if(checkShopUser($three_id,$shop_id)){

            $User->where('user_id = '.$three_id)->setDec('three_level',$count);

            $User->where('user_id = '.$three_id)->setDec('total_level',$count);

        }

    }

}



function checkShopUser($user_id,$shop_id){

    return M('User')->where('user_id = '.$user_id.' AND shop_id = '.$shop_id.' AND is_user_del = 0')->getField(1);

}



/**

 * 通过微信接口将长链接转短链接

 *  

 */

function wx_shorturl($long_url) {

    $url = 'https://api.weixin.qq.com/cgi-bin/shorturl?access_token=' . get_weixin_access_token();

    $param = array('action'=>'long2short', 'long_url'=>$long_url);

    $res = json_decode(curl_post($url, $param), true);

    if ($res['short_url']) return $res['short_url'];

    else return $long_url;

}



/**

 * curl获取内容

 */

function curl_post($url, $postFields = null){

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_FAILONERROR, false);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);



    //https 请求

    if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    }



    if (is_array($postFields) && 0 < count($postFields))

    {

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));

    }

    $reponse = curl_exec($ch);



    if (curl_errno($ch))

    {

        throw new Exception(curl_error($ch),0);

    }

    else

    {

        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if (200 !== $httpStatusCode)

        {

            throw new Exception($reponse,$httpStatusCode);

        }

    }

    curl_close($ch);

    return $reponse;

}



/**

 * 成为分销商设等级

 *  

 */

function AgentRankConfig($user_id){

    $shop_id = M('User')->where('user_id = ' . $user_id)->getField('shop_id');

    $is_agent_rank = config('is_agent_rank', null, $shop_id);

    if($is_agent_rank){

        $set_agent_rank = config('set_agent_rank', null, $shop_id);

        if($set_agent_rank >0){

            M('User')->where('user_id = '.$user_id)->save(array('agent_rank_id'=>$set_agent_rank));

        }

    }

}



/*



 *根据新浪IP查询接口获取IP所在地



 */



function getIPLoc_sina($queryIP){

    $url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$queryIP;

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回

    $location = curl_exec($ch);

    $location = json_decode($location);

    curl_close($ch);

    $array = array();

    if($location===FALSE) return "";

    $array[0] = $location->province;

    $array[1] = $location->city;

    return $array;



}



/**

 * 获取账号

 *  

 */

function adminAccount(){

    if(is_admin()){

        $aid = is_admin();

        $account = M('Admin')->where('admin_id = '.$aid)->getField('account');

    }elseif(is_login()){

        $sid = is_login();

        $mobile = M('Seller')->where('seller_id = '.$sid)->getField('mobile');

        $account  = decrypt($mobile);

    }

    return $account;

}



/**

 * 获取积分类型

 *  

 */

function getPointType($type) {

    switch ($type) {

        case 0:

            $info = '订单送积分';

            break;

        case 1:

            $info = '游戏奖励积分';

            break;

        case 2:

            $info = '外部订单积分';

            break;

        case 3:

            $info = '绑定账号后积分迁移';

            break;

        case 4:

            $info = '卖家调整';

            break;

        case 5:

            $info = '签到送积分';

            break;

        case 6:

            $info = '赠送积分';

            break;

        case 7:

            $info = '兑换优惠券';

            break;

        case 8:

            $info = '玩游戏';

            break;

        case 9:

            $info = '积分兑换商品';

            break;

        case 10:

            $info = '分享送积分';

            break;

        case 11:

            $info = '充值送积分';

            break;

        case 12:

            $info = '关注送积分';

            break;

        case 13:

            $info = '删除积分订单返还';

            break;

        case 14:

            $info = '兑换红包';

            break;

        case 15:

            $info = '删除订单返还';

            break;

        case 16:

            $info = '关闭订单返还';

            break;

        case 17:

            $info = '下级消费送积分订单';

            break;

        case 18:

            $info = '卖家恢复删除订单扣除返还积分';

            break;

    }

    return $info;

}



/**

 * 获取积金类型

 *  

 */

function getFundType($type) {

    switch ($type) {

        case 0:

            $info = '订单送金币';

            break;

        case 0:

            $info = '订单送金币';

            break;

        case 1:

            $info = '游戏奖励金币';

            break;

        case 2:

            $info = '外部订单金币';

            break;

        case 3:

            $info = '绑定账号后积分迁移';

            break;

        case 4:

            $info = '卖家调整';

            break;

        case 5:

            $info = '签到送金币';

            break;

        case 6:

            $info = '赠送积分';

            break;

        case 7:

            $info = '兑换优惠券';

            break;

        case 8:

            $info = '玩游戏';

            break;

        case 9:

            $info = '金币兑换商品';

            break;

        case 10:

            $info = '分享送金币';

            break;

        case 11:

            $info = '充值送金币';

            break;

        case 12:

            $info = '注册送金币';

            break;

        case 13:

            $info = '删除金币订单返还';

            break;

        case 14:

            $info = '兑换红包';

            break;

        case 15:

            $info = '删除订单返还';

            break;

        case 16:

            $info = '关闭订单返还';

            break;

        case 17:

            $info = '下级消费送金币订单';

            break;

        case 18:

            $info = '卖家恢复删除订单扣除返还金币';

            break;

    }

    return $info;

}



/**

 * 获取店铺版本

 *  

 */

function getVersion($version_id) {

    switch ($version_id) {

        case 1:

            $info = '免费版';

            break;

        case 2:

            $info = '标准版';

            break;

        case 3:

            $info = '企业版';

            break;

        case 4:

            $info = '集团版';

            break;

        case 5:

            $info = '渠道版';

            break;

    }

    return $info;

}



/**

 * 生成缩略图

 *

 * 只支持生成 gif、jpg、png 的格式的图片缩略图（GIF不支持动画）

 *

 *  

 * @param string $source_path 原图片地址

 * @param integer $target_width 缩略图宽度

 * @param integer $target_height 缩略图高度

 * @return void

 */

function image_cropper($source_path, $target_width, $target_height)

{

    $source_info   = getimagesize($source_path);

    $source_width  = $source_info[0];

    $source_height = $source_info[1];

    $source_mime   = $source_info['mime'];

    $source_ratio  = $source_height / $source_width;

    $target_ratio  = $target_height / $target_width;



    if ($source_ratio > $target_ratio) { // 源图过高

        $cropped_width  = $source_width;

        $cropped_height = $source_width * $target_ratio;

        $source_x = 0;

        $source_y = ($source_height - $cropped_height) / 2;

    } elseif ($source_ratio < $target_ratio) { // 源图过宽

        $cropped_width  = $source_height / $target_ratio;

        $cropped_height = $source_height;

        $source_x = ($source_width - $cropped_width) / 2;

        $source_y = 0;

    } else { // 源图适中

        $cropped_width  = $source_width;

        $cropped_height = $source_height;

        $source_x = 0;

        $source_y = 0;

    }



    switch ($source_mime)

    {

        case 'image/gif':

            $source_image = imagecreatefromgif($source_path);

            break;



        case 'image/jpeg':

            $source_image = imagecreatefromjpeg($source_path);

            break;



        case 'image/png':

            $source_image = imagecreatefrompng($source_path);

            break;



        default:

            return false;

            break;

    }



    $target_image  = imagecreatetruecolor($target_width, $target_height);

    $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);



    // 裁剪

    imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);

    // 缩放

    imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);



    switch ($source_mime)

    {

        case 'image/gif':

            header('Content-Type: image/gif');

            imagegif($target_image);

            break;



        case 'image/jpeg':

            header('Content-Type: image/jpeg');

            imagejpeg($target_image);

            break;



        case 'image/png':

            header('Content-Type: image/png');

            imagepng($target_image);

            break;



        default:

            return false;

            break;

    }



    imagedestroy($source_image);

    imagedestroy($target_image);

    imagedestroy($cropped_image);

}



function list_class($list,$pid=0){

    $arr=array();

    foreach($list as $v){

        if($v['parent_id'] == $pid){

            $arr[]=$v;

            $arr=array_merge($arr,list_class($list,$v['class_id']));

        }

    }

    return $arr;

}





/**

 * 获取微信配置

 *  

 */

function wxConfig($shop_id=SHOP_ID){

    $shop_info = M('Shop')->where('shop_id = ' . $shop_id.' AND status = 1')->field('seller_id,wx_pay_mchid,wx_pay_key')->find();

    $wx_info = M('PubWeixin')->where('seller_id = ' . $shop_info['seller_id'])->field('app_id, app_secret')->find();

    $wx_info['wx_pay_mchid'] = $shop_info['wx_pay_mchid'];

    $wx_info['wx_pay_key'] = $shop_info['wx_pay_key'];

    return $wx_info;

}



/**

 * 带证书的curl方法

 * 提供 $cert 和 $private 需要同时使用，使用了 $rootca 就不要使用 $cert 和 $private，这两种证书方式任选其中一种

 * 建议使用 $rootca 证书

 **/

function curl_post_ssl($url, $vars, $rootca='', $cert='', $private='', $second=30, $aHeader=array())

{

    $ch = curl_init();

    //超时时间

    curl_setopt($ch, CURLOPT_TIMEOUT, $second);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);



    //这里设置代理，如果有的话

    //curl_setopt($ch, CURLOPT_PROXY, '10.206.30.98');

    //curl_setopt($ch, CURLOPT_PROXYPORT, 8080);

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    if(defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')){

        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

    }

    curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);

    //以下两种方式需选择一种



    //第一种方法，cert 与 key 分别属于两个.pem文件



    //默认格式为PEM，可以注释

    if ($cert) {

        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');

        //微信支付已提供

        //微信支付中的 cert.pem 也可使用 openssl pkcs12 -clcerts -nokeys -in apiclient_cert.p12 -out apiclient_cert.pem 生成

        //curl_setopt($ch, CURLOPT_SSLCERT, getcwd().'/apiclient_cert.pem');

        curl_setopt($ch, CURLOPT_SSLCERT, $cert);

    }



    //默认格式为PEM，可以注释

    if ($private) {

        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');

        //微信支付已提供

        //微信支付中的 private.pem 也可使用 openssl pkcs12 -nocerts -in apiclient_cert.p12 -out apiclient_key.pem 生成

        //curl_setopt($ch, CURLOPT_SSLKEY, getcwd().'/apiclient_key.pem');

        curl_setopt($ch, CURLOPT_SSLKEY, $private);

    }



    //第二种方式，两个文件合成一个.pem文件，是个CA证书

    if ($rootca) {

        //微信支付已提供

        //curl_setopt($ch, CURLOPT_SSLCERT, getcwd().'/rootca.pem');

        curl_setopt($ch, CURLOPT_SSLCERT, $rootca);

    }



    if(count($aHeader) >= 1){

        curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);

    }



    if (is_array($vars) && 0 < count($vars))

    {

        $postBodyString = "";

        foreach ($vars as $k => $v)

        {

            $postBodyString .= "$k=" . urlencode($v) . "&";

        }

        unset($k, $v);

        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));

    } elseif ($vars) {

        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);

    }



    $data = curl_exec($ch);



    if($data){

        curl_close($ch);

        return $data;

    } else {

        $error = curl_errno($ch);

        $curl_error = curl_error($ch);

        //echo "call faild, errorCode:$error\n error:$curl_error";

        $array = array('return_code'=>'FAIL','return_msg'=>$curl_error,'err_code'=>$error);

        $xml_param =  Org\Util\Util::arrayToXml($array);

        curl_close($ch);

        return $xml_param;

    }

}



/**

 * 礼品订单状态

 *

 */

function prize_order_status($type){

    switch($type){

        case 0:

            $status_name = '待买家填写收货地址';

            break;

        case 1:

            $status_name = '待发货';

            break;

        case 2:

            $status_name = '待收货';

            break;

        case 3:

            $status_name = '已收货';

            break;

        case 4:

            $status_name = '已关闭';

            break;

    }

    return $status_name;

}



/**

 * 奖品等级

 */

function prize_level_type($type){

    switch($type){

        case 1:

            $status_name = '一等奖';

            break;

        case 2:

            $status_name = '二等奖';

            break;

        case 3:

            $status_name = '三等奖';

            break;

        case 4:

            $status_name = '普通奖';

            break;

        default:

            $status_name = '';

    }

    return $status_name;

}



/**

 * 代理商等级名称

 *  

 */

function dls_rank_name($rank){

    switch ($rank) {

        case 1:

            $rank_name = !config('one_dls_name') ? '一级代理商' : config('one_dls_name');

            break;

        case 2:

            $rank_name = !config('two_dls_name') ? '二级代理商' : config('two_dls_name');

            break;

        case 3:

            $rank_name = !config('three_dls_name') ? '三级代理商' : config('three_dls_name');

            break;

        case 4:

            $rank_name = !config('four_dls_name') ? '四级代理商' : config('four_dls_name');

            break;

        default:

            $rank_name = '';

    }

    return $rank_name;

}



/**

 * 判断是否有代理商功能

 *  

 */

function has_dls($shop_id = SHOP_ID) {

    $version_id = M('Shop')->where('shop_id = ' . $shop_id)->getField('version_id');

    $priv_str = M('Version')->where('version_id = ' . $version_id)->getField('priv_str');

    if (strpos($priv_str, ',0478,') !== false) return true;

    else return false;

}



/**

 * 更新会员门店,员工信息

 *  

 */

function update_user_store($user_id, $shop_id=SHOP_ID) {

    if (!has_dls($shop_id)) return;



    $User = M('User');

    $UserStore = M('UserStore');



    $map = array('user_id'=>$user_id);



    // 门店不需要更新

    $info = $UserStore->where($map)->find();

    if ($info['user_type'] == 3) return;



    // 直属上级id

    $superior_user_id = $User->db(1, 'MASTER_DB')->where($map)->getField('superior_user_id');

    $superior_store_info = $UserStore->where(array('user_id'=>$superior_user_id))->find();



    if ($superior_store_info) {

        $map = array();

        $data = $superior_store_info;

        $data['user_id'] = $user_id;

        $data['user_type'] = 0;

        if (!$info) {

            $UserStore->add($data);

        } else {

            unset($data['user_id']);

            $map = array('user_id'=>$user_id);

            $UserStore->where($map)->save($data);

        }



        $lowers = usersLower($user_id, $shop_id);

        while ($lowers) {

            // 过滤门店

            $ones = (array)$UserStore->where(array('user_id' => array('in', $lowers), 'user_type' => 3))->getField('user_id', true);

            $lowers = array_diff($lowers, $ones);



            foreach ($lowers as $k => $id) {

                if ($map) {

                    $map['user_id'] = $id;

                    $res = $UserStore->where($map)->save($data);

                } else {

                    $data['user_id'] = $id;

                    $res = $UserStore->add($data);

                }

                if (!$res) unset($lowers[$k]);

            }



            $lowers = usersLower($lowers, $shop_id);

        }

    } else {

        $map = array('user_id'=>$user_id);

        $UserStore->where($map)->delete();

        $lowers = usersLower($user_id, $shop_id);

        while ($lowers) {

            // 过滤门店

            $ones = (array)$UserStore->where(array('user_id' => array('in', $lowers), 'user_type' => 3))->getField('user_id', true);

            $lowers = array_diff($lowers, $ones);



            foreach ($lowers as $k => $id) {

                $map['user_id'] = $id;

                $res = $UserStore->where($map)->delete();

                if (!$res) unset($lowers[$k]);

            }



            $lowers = usersLower($lowers, $shop_id);

        }

    }

}



/**

 * 更新会员代理商信息

 *  

 */

function update_user_dls($user_id, $shop_id=SHOP_ID) {

    if (!has_dls($shop_id)) return;



    $User = M('User');

    $UserDls = M('UserDls');



    $map = array('user_id'=>$user_id);



    // 一级代理商不需要更新

    $info = $UserDls->where($map)->find();

    if ($info['is_dls'] && $info['rank'] == 1) return;

    if ($info) {

        if (is_null($info['superior_dls_id'])) $info['superior_dls_id'] = array('exp', 'is null');

        if (is_null($info['top_dls_id'])) $info['top_dls_id'] = array('exp', 'is null');

        if (is_null($info['three_dls_id'])) $info['three_dls_id'] = array('exp', 'is null');

    }



    // 直属上级id

    $superior_user_id = $User->db(1, 'MASTER_DB')->where($map)->getField('superior_user_id');



    $superior_dls_info = $UserDls->where(array('user_id'=>$superior_user_id))->find();

    if ($superior_dls_info) {

        $data = $map = array();

        if (!$info) {

            $data = array('user_id' => $user_id, 'shop_id' => $shop_id, 'is_dls' => 0, 'end_time' => null, 'rank' => null, 'ratio' => null, 'ratio_info' => null,

                'superior_dls_id' => $superior_dls_info['superior_dls_id'], 'top_dls_id' => $superior_dls_info['top_dls_id'], 'three_dls_id' => $superior_dls_info['three_dls_id']);

            $UserDls->add($data);

        } elseif (!$info['is_dls']) {

            $data = array('superior_dls_id' => $superior_dls_info['superior_dls_id'], 'top_dls_id' => $superior_dls_info['top_dls_id'], 'three_dls_id' => $superior_dls_info['three_dls_id']);

            $map = array('user_id' => $user_id, 'superior_dls_id'=>$info['superior_dls_id'], 'top_dls_id' => $info['top_dls_id'], 'three_dls_id' => $info['three_dls_id']);

            $UserDls->where($map)->save($data);

        } elseif ($info['is_dls'] && $info['rank'] == 2) {

            $data = array('superior_dls_id' => $superior_dls_info['superior_dls_id']);

            $map = array('user_id' => $user_id, 'superior_dls_id'=>$info['superior_dls_id']);

            $UserDls->where($map)->save($data);

        } elseif ($info['is_dls'] && $info['rank'] == 3) {

            $data = array('superior_dls_id' => $superior_dls_info['superior_dls_id'], 'top_dls_id' => $superior_dls_info['top_dls_id']);

            $map = array('user_id' => $user_id, 'superior_dls_id'=>$info['superior_dls_id'], 'top_dls_id' => $info['top_dls_id']);

            $UserDls->where($map)->save($data);

        }

        if ($data) {

            $lowers = usersLower($user_id, $shop_id);

            while ($lowers) {

                // 过滤一级代理商

                $ones = (array)$UserDls->where(array('user_id' => array('in', $lowers), 'is_dls' => 1, 'rank' => 1))->getField('user_id', true);

                $lowers = array_diff($lowers, $ones);



                foreach ($lowers as $k => $id) {

                    if ($map) {

                        $map['user_id'] = $id;

                        $res = $UserDls->where($map)->save($data);

                    } else {

                        $data['user_id'] = $id;

                        $res = $UserDls->add($data);

                    }

                    if (!$res) unset($lowers[$k]);

                }



                $lowers = usersLower($lowers, $shop_id);

            }

        }

    } else {

        $data = $map = array();

        if ($info && !$info['is_dls']) {

            $data = array('superior_dls_id' => null, 'top_dls_id' => null, 'three_dls_id' => null);

            $map = array('user_id' => $user_id, 'superior_dls_id'=>$info['superior_dls_id'], 'top_dls_id' => $info['top_dls_id'], 'three_dls_id' => $info['three_dls_id']);

            $UserDls->where($map)->save($data);

        } elseif ($info['is_dls'] && $info['rank'] == 2) {

            $data = array('superior_dls_id' => null);

            $map = array('user_id' => $user_id, 'superior_dls_id'=>$info['superior_dls_id']);

            $UserDls->where($map)->save($data);

        } elseif ($info['is_dls'] && $info['rank'] == 3) {

            $data = array('superior_dls_id' => null, 'top_dls_id' => null);

            $map = array('user_id' => $user_id, 'superior_dls_id'=>$info['superior_dls_id'], 'top_dls_id' => $info['top_dls_id']);

            $UserDls->where($map)->save($data);

        }

        if ($data) {

            $lowers = usersLower($user_id, $shop_id);

            while ($lowers) {

                // 过滤一级代理商

                $ones = (array)$UserDls->where(array('user_id' => array('in', $lowers), 'is_dls' => 1, 'rank' => 1))->getField('user_id', true);

                $lowers = array_diff($lowers, $ones);

                foreach ($lowers as $k => $id) {

                    $map['user_id'] = $id;

                    $res = $UserDls->where($map)->save($data);

                    if (!$res) unset($lowers[$k]);

                }

                $lowers = usersLower($lowers, $shop_id);

            }

        }

    }

}



/**

 * 返回会员的直属下级

 *  

 */

function usersLower($users, $shop_id = SHOP_ID) {

    if (is_int($users)) $users = strval($users);

    $map = array('shop_id'=>$shop_id, 'superior_user_id'=>array('in', $users));

    return M('User')->where($map)->getField('user_id', true);

}



/**

 * 更新公众号类型

 *  

 */

function update_account_type($seller_id = SID) {

    $long_url = 'http://www.diankuai.com';

    $url = 'https://api.weixin.qq.com/cgi-bin/shorturl?access_token=' . get_weixin_access_token($seller_id);

    $param = array('action'=>'long2short', 'long_url'=>$long_url);

    $res = json_decode(curl_post($url, $param), true);



    if ($res['errcode'] == 48001) {

        $account_type = 2;

    } elseif ($res['errcode'] == 0) {

        $account_type = 1;

    } else {

        $account_type = 0;

    }



    if ($account_type) {

        M('PubWeixin')->where('seller_id = ' . $seller_id . ' AND type = 1')->setField('account_type', $account_type);

        $shop_id = M('Shop')->where('seller_id = ' . $seller_id)->getField('shop_id');

        S('account_type' . $shop_id, null);

    }

}



/**

 * 计算两个经纬度之间的距离

 *  

 */

function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {

    $theta = $longitude1 - $longitude2;

    $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));

    $miles = acos($miles);

    $miles = rad2deg($miles);

    $miles = $miles * 60 * 1.1515;

    $kilometers = round($miles * 1.609344, 2);

    return $kilometers;

}





// +---------------------------------------------------------------------------

// | 静态缓存函数

// +---------------------------------------------------------------------------

/**

 * 取字符串的md5值中的第一个字符

 * @param string $str

 * @return string

 */

function get_md5_1($str) {

    return substr(md5($str), 0, 1);

}



/**

 * 取字符串的md5值中的第二个字符

 * @param string $str

 * @return string

 */

function get_md5_2($str) {

    return substr(md5($str), 1, 1);

}



/**

 * 取字符串的md5值中的第三个字符

 * @param string $str

 * @return string

 */

function get_md5_3($str) {

    return substr(md5($str), 2, 1);

}

// +---------------------------------------------------------------------------

// | end静态缓存函数

// +---------------------------------------------------------------------------

/**

 * 生成随机字符串

 *  

 * @param $length 长度

 * @return null|string

 */

function getRandChar($length){

    $str = null;

    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";

    $max = strlen($strPol)-1;



    for($i=0;$i<$length;$i++){

        $str.=$strPol[rand(0,$max)];

    }



    return $str;

}



/**

 * 判断是否绑定域名导入导出

 *  

 */

function isCheckBind(){

    if(C('DAO_URL')){

        return true;

    }else{

        return false;

    }

}



/**

 * 比较会员等级

 *  

 */

 function comparisonRank($rank_id1,$rank_id2,$type=1,$is_only=1){
    if(strpos($rank_id2,',')){

        $rank_ids = explode(',',$rank_id2);
        $status = 0;
        foreach ($rank_ids as $key => $rank_id2) {

            if($is_only == 2){

                if($rank_id1 == $rank_id2){

                     $status = 1;

                }
            }else{

                if($type == 1){
                    $level1 = getRankLevel($rank_id1);

                    $level2 = getRankLevel($rank_id2);

                }else{

                    $level1 = getAgentLevel($rank_id1);

                    $level2 = getAgentLevel($rank_id2);

                }

                if($level1>=$level2){

                    $status = 1;

                }
            }     
        }
        if($status){
            return true;
        }else{
            return false;    
        }
    }else{
        if($is_only == 2){

            if($rank_id1 == $rank_id2){

                return true;

            }else{

                return false;

            }

        }else{

            if($type == 1){

                $level1 = getRankLevel($rank_id1);

                $level2 = getRankLevel($rank_id2);

            }else{

                $level1 = getAgentLevel($rank_id1);

                $level2 = getAgentLevel($rank_id2);

            }

            if($level1<$level2){

                return false;

            }else{

                return true;

            }

        }   
    }
    

}



/**

 * 获取会员权重

 *  

 */

function getRankLevel($rank_id){

    $level = M('UserRank')->where('rank_id = '.$rank_id)->getField('level');

    return $level?$level:0;



}

/**

 * 获取分销商权重

 *  

 */

function getAgentLevel($rank_id){

    $level = M('AgentRank')->where('agent_rank_id = '.$rank_id)->getField('agent_level');

    return $level?$level:0;

}



/**

 * 微夺宝订单状态

 *  

 * 0:等待买家填写收货地址;1：等待卖家发货; 2：等待买家确认收货 ; 3：买家确认收货;4:关闭订单;

 */

function crowd_status($status){

    switch ($status) {

        case 0:

            $info = '等待买家填写收货地址';

            break;

        case 1:

            $info = '等待卖家发货';

            break;

        case 2:

            $info = '等待买家确认收货';

            break;

        case 3:

            $info = '交易完成';

            break;

        case 4:

            $info = '关闭订单';

            break;

        default:

            $info = '';

    }

    return $info;

}



/**

 * 字符打*

 * @param $sourceString

 * @param int $length

 * @param string $appendChar

 * @return string

 */

function stringCustomerAppend($sourceString, $length = 1, $appendChar = '*'){

    $distLength = mb_strlen($sourceString, 'utf-8');

    $result = mb_substr($sourceString, 0, $length, 'utf-8') . str_repeat($appendChar, $distLength-$length);

    return $result;

}



/**

 * 生成前台地址,自动加上店铺id(sid)

 *  

 * @param string $url 链接地址

 * @return string

 */

function preview_url($url) {

    // 判断链接里是否带有店铺id

    $arr_url = explode('/', $url);

    if (!in_array('sid', $arr_url)) {

        $count = count($arr_url);

        $arr_url[$count-1] = preg_replace('/^(.*)\.html$/', '$1', $arr_url[$count-1]);

        array_push($arr_url, 'sid', SHOP_ID);

        $url = implode('/', $arr_url) . '.html';

    }

    $http_host = rtrim($_SERVER['HTTP_HOST'], '.');

    if(defined('SHOP_ID')){

        $domain = M('Domain')->where('shop_id = '.SHOP_ID.' AND status = 1')->cache(true,300)->getField('domain_name');

        if($domain && strpos($domain,'http') === false){

            $domain = 'http://'.$domain;

        }

    }

    if($domain){

        return $domain . $url;

    }else{

        if((preg_match('/[m|mob](\d+)?\.w[x|i]fenxiao.com/', $http_host) || preg_match('/mob(\d+)?\.91weimai.com/', $http_host)) && (C('AFTER_DOMAIN') == 'mp.wxfenxiao.com' || C('AFTER_DOMAIN') == 'cp.wifenxiao.com')) {

            return 'http://' . $http_host . $url;

        } else {

            return C('FRONT_URL') . $url;

        }

    }

}



/**

 * 判断是否含有屏蔽词

 *  

 */

function limit_word($str) {

//    return false; // 过滤词有问题，暂时先不判断

    if (!S('limitWord')) {

        $file = './Public/limitWord.json';

        S('limitWord', file_get_contents($file));

    }

    $limitWord = S('limitWord');

    $arr_limit = explode(',', $limitWord);

    foreach ($arr_limit as $v) {

        if (strpos($str, $v) !== false) {

            return $v;

        }

    }

    return false;

}



/*

 * 根据属性ＩＤ获取属性名

 * @param int property_id

 *  

 */

function get_property($property_id){



    return D('Property')->where('property_id = '.$property_id)->getField('property_name');

}

function get_valproperty($vid){

    return D('PropertyValue')->where('property_value_id = '.$vid)->getField('property_value');

}

/*

 * 根据淘宝属性ＩＤ获取属性名

 * @param $tb_property_id

 *  

 */

function get_tb_property($tb_property_id,$sid){



    $a =  M('TbProperty')->where('pid = '.$tb_property_id.' AND cat_id = '.$sid)->getField('property_name');

    return $a;

}

function get_tb_valproperty($vid,$pid,$sid){

    $return = M('TbPropertyValue')->where('vid = '.$vid.' AND cat_id = '.$sid.' AND pid = '.$pid)->getField('value_name');

    if(!$return){

        $return =M('TaobaoPropsCustom')->where(array('custom_id'=>$vid,'shop_id'=>SHOP_ID))->getField('value_name');

    }

    return  $return;

}



function export_express(){

    // 解析csv文件

    $file = './sql.txt';

    $handle = fopen($file, 'r');

    $n = 0;

    while ($data = fgetcsv($handle, 0, "\t")) {

        $n++;

        if ($n <2 ) continue;

        $arr = array(

            'express_name'=>$data[0],

            'express_code'=>$data[1]

        );

        M('Express')->add($arr);

    }

}



/**

 * 获取快递公司

 *  

 */

function getExpress($status=null){

    //快递公司

    $express =  M('Express')->order('serial')->cache(true)->select();

    if(empty($express)){

        $return = C('EXPRESS');

    }else{

        foreach($express as $v){

            $return[$v['express_id']] = $v['express_name'];

        }

    }

    if(!is_null($status)){

        return $return[$status];

    }else{

        return $return;

    }

}



/**

 * 是否开团成功

 */

if(!function_exists('GroupShoppingIsSuccess')){

    function GroupShoppingIsSuccess($id, $user_id, $order_id, $shopId = SHOP_ID){

        if(!is_numeric($id) || $id <=0){

            return true;

        }

        $mGroupShopping = M('GroupShopping');

        $mOrder = M('Order');

        // 已经付款的订单笔数超过即可

        $info = $mGroupShopping->where(array('id'=>$id, 'shop_id'=>$shopId))->find();

        if(!$info){

            // 团购不存在

            return true;

        }

        $info['shop_id'] = intval($info['shop_id']);

        $where = array(

            'shop_id'           => $info['shop_id'],

            'group_shopping_id' => intval($info['id']),

            'user_id' => $user_id,

            'order_id' => $order_id

        );



        $group_orderinfo = M('GroupShoppingOrder')->where($where)->field('tuan_id,is_tuan,tuan_order_id')->find();

        if($group_orderinfo['is_tuan'] == 1){

            return true;

        }else if($group_orderinfo['is_tuan'] == 0){

            return false;

        }

        //是否更新拼团状态

        $is_tuan = false;

        if($info['aggregation_type'] == 1) {             //小团

            $tuan_id = $group_orderinfo['tuan_id'];

            if($tuan_id) {

                $count = $mOrder->alias('o')->join('__GROUP_SHOPPING_ORDER__ s on s.order_id = o.order_id')

                    ->where(array(

                        'shop_id' => $shopId,

                        's.group_shopping_id' => $info['id'],

                        'tuan_id' => $tuan_id,

                        'status' => array('IN', implode(',', array('1','2','3','6'))),

                        's.tuan_order_id'=> $group_orderinfo['tuan_order_id'],

                    ))->count('distinct s.user_id');

                $is_tuan = $count >= intval($info['num']);

            }

        } else if($info['aggregation_type'] == 2){        //阶梯团

            $is_tuan = $info['end_time'] < time();

        }else{                                                //大团

            $where = array(

                'dc_shop'           => $info['shop_id'],

                'group_shopping_id' => $info['id'],

                'status'            => array('IN', implode(',', array('1','2','3','6'))),        // 必须是已经付款的或者

            );

            $sql = $mOrder->where($where)->group('user_id')->buildSql();

            $sql = ' SELECT COUNT(*) AS c FROM ' . $sql . ' AS t';

            $count = M()->query($sql);

            $count = intval($count[0]['c']);

            $is_tuan = $count >= intval($info['num']);

        }

        //当拼团成功后，更新团购订单，小团批量，阶梯团和大团则单个更新

        if($is_tuan){

            M('GroupShoppingOrder')->where(array('tuan_order_id'=>$group_orderinfo['tuan_order_id'],'group_shopping_id'=>$info['id']))->setField('is_tuan',1);

        }

        return $is_tuan;

    }

}



/**

 * 拼团参与人数

 */

function GroupShoppingNum($id, $user_id, $order_id, $shopId = SHOP_ID){

    $id = intval($id);

    if(!$id){

        return true;

    }

    $mGroupShopping = M('GroupShopping');

    $mOrder = M('Order');

    // 已经付款的订单笔数超过即可

    $info = $mGroupShopping->where(array('id'=>$id, 'shop_id'=>$shopId))->find();

    if(!$info){

        // 团购不存在

        return true;

    }

    $info['shop_id'] = intval($info['shop_id']);

    if($info['aggregation_type'] == 1) {

        $where = array(

            'shop_id'           => $info['shop_id'],

            'group_shopping_id' => intval($info['id']),

            'user_id' => array('eq', $user_id),

            'order_id' => $order_id

        );

        

        $group_orderInfo = M('GroupShoppingOrder')->where($where)->field('tuan_id,tuan_order_id')->find();

        $tuan_id = $group_orderInfo['tuan_id'];

        if($tuan_id) {

            $count = $mOrder->alias('o')->join('__GROUP_SHOPPING_ORDER__ s on s.order_id = o.order_id')

                ->where(array(

                    'shop_id' => $shopId,

                    's.group_shopping_id' => intval($info['id']),

                    'tuan_id' => $tuan_id,

                    'status' => array('IN', implode(',', array('1','2','3','6'))),

                    's.tuan_order_id'=> $group_orderInfo['tuan_order_id'],

                ))->count('distinct s.user_id');

        }

    } else {

        $where = array(

            'dc_shop'           => $info['shop_id'],

            'group_shopping_id' => intval($info['id']),

            'status'            => array('IN', implode(',', array('1','2','3','6'))),        // 必须是已经付款的或者

        );

        $sql = $mOrder->where($where)->group('user_id')->buildSql();

        $sql = ' SELECT COUNT(*) AS c FROM ' . $sql . ' AS t';

        $count = M()->query($sql);

        $count = intval($count[0]['c']);

    }        



    return $count;

}



/*

 * 根据省份ＩＤ获取省份名

* @param int province_id

*  

*/

function get_provincename($province_id){

    static $result = array();

    if(!$result){

        $result = M('Province')->cache(true)->getField('province_id,province_name', true);

    }

    return $result[$province_id];

    //return D('Province')->where('province_id = '.$province_id)->getField('province_name');

}

/*

 * 根据城市ＩＤ获取城市名

* @param int city_id

*  

*/

function get_cityname($city_id){

    static $result = array();

    if(!$result){

        $result = M('City')->cache(true)->getField('city_id,city_name', true);

    }

    return $result[$city_id];

    //return D('City')->where('city_id = '.$city_id)->getField('city_name');

}

/*

 * 根据区县ＩＤ获取区县名

* @param int area_id

*  

*/

function get_areaname($area_id){

    if (!$area_id) return '';

    static $result = array();

    if(!$result){

        $result = M('Area')->cache(true)->getField('area_id,area_name', true);

    }

    return $result[$area_id];



    //return D('Area')->where('area_id = '.$area_id)->getField('area_name');

}



function seller_msg_content($content,$nickname,$order_no=null){

    $content =  str_replace('{插入昵称}',$nickname,$content);

    $content =  str_replace('{插入订单号}',$order_no,$content);

    $content = addslashes(content_format($content));



    return $content;

}



function user_msg_content($content,$shop_title,$count,$user_id=null){

    $content =  str_replace('{插入店铺}',$shop_title,$content);

    $content =  str_replace('{插入会员个数}',$count,$content);

    $content =  str_replace('{插入ID号}',$user_id,$content);

    $content = addslashes(content_format($content));

    return $content;

}



/**

 * 获取ip对应的地址

 * @param string $ip

 * @return bool|mixed

 */

function get_ip_lookup($ip){

    $res = @curl('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);

    if(empty($res)){ return false; }

    $jsonMatches = array();

    preg_match('#\{.+?\}#', $res, $jsonMatches);

    if(!isset($jsonMatches[0])){ return false; }

    $json = json_decode($jsonMatches[0], true);

    if(isset($json['ret']) && $json['ret'] == 1){

        $json['ip'] = $ip;

        unset($json['ret']);

    }else{

        return false;

    }

    return $json;

}



/**

 * 获取IP地址(淘宝接口)

 */

function get_ip_address($ip) {

    $res = curl('http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip);

    return json_decode($res, true);

}





/**

 * 成为分销商生成分销名片

 *  

 */

function generateAgentCard($user_id,$shop_id=SHOP_ID){

    if(C('SYS_URL')){

        $data = array('user_id'=>$user_id,'shop_id'=>$shop_id);

        $data['sign'] = sys_sign(C('SYS_SIGN'),$data);

        curl(C('SYS_URL').'/SysScript/generateAgentCard',$data);

    }else{

        system('/usr/local/php/bin/php index.php Public/sendCard/user_id/' . $user_id . '/type/1/sid/' . $shop_id . ' > /dev/null &');

        system('/usr/local/php5.3/bin/php index.php Public/sendCard/user_id/' . $user_id . '/type/1/sid/' . $shop_id . ' > /dev/null &');

    }

}



/**

 * 签名

 *  

 */

function sys_sign($secret,$arr){

    ksort($arr); //将数组按键名排序，按键名升序排列

    $tmp = '';

    foreach ($arr as $k => $v) {

        if (is_array($v)) { //如果当前值为数组时则该数组内的各项也要拼接到字符串中

            ksort($v); //按键名排序

            foreach ($v as $m => $n) {

                $tmp .= $m . $n; //拼接字符串

            }

        } else {

            $tmp .= $k . $v; //拼接字符串

        }

    }

    return strtoupper(md5($secret . $tmp . $secret)); //先用md5加密，再转成大写

}

/**

 * 获取退货状态

 * @param int $type　int $status

 *  

 * @return string

 */

function get_exchange($status,$type){

    if($status === '0'){

        switch ($type) {

            case 1:

                $info = '处理换货申请';

                break;

            case 2:

                $info = '处理退货申请';

                break;



            default:

                $info = '';

        }

    }elseif($status == 1){

        switch ($type) {

            case 1:

                $info = '换货成功';

                break;

            case 2:

                $info = '退货成功';

                break;



            default:

                $info = '';

        }

    }elseif($status == 2){

        switch ($type) {

            case 1:

                $info = '换货失败';

                break;

            case 2:

                $info = '退货失败';

                break;



            default:

                $info = '';

        }

    }elseif($status == 3){

        $info = '维权结束';

    }



    return $info;

}



/**

 *生成云购码

 * 

 */

function content_get_go_codes($CountNum,$item_id,$expect_num,$shop_id=SHOP_ID,$len=3000){

    $CrowdCode = M('CrowdCodes');

    $num = ceil($CountNum/$len);

    $code_i = $CountNum;

    if($num == 1){

        $codes=array();

        for($i=1;$i<=$CountNum;$i++){

            $codes[$i]=10000000+$i;

        }

        shuffle($codes);$codes=serialize($codes);

        $query = $CrowdCode->add(array('shop_id'=>$shop_id,'item_id'=>$item_id,'expect_num'=>$expect_num,'codes_len'=>$CountNum,'codes_i'=>1,'codes'=>$codes,'codes_tmp'=>$codes));

        unset($codes);

        if($query){

            M('ItemCrowd')->where('shop_id = '.$shop_id.' AND item_id = '.$item_id.' AND expect_num = '.$expect_num.' AND status = 0')->setField('status',1);

        }

        return $query;

    }

    $query_1 = true;

    for($k=1;$k<$num;$k++){

        $codes=array();

        for($i=1;$i<=$len;$i++){

            $codes[$i]=10000000+$code_i;

            $code_i--;

        }shuffle($codes);$codes=serialize($codes);

        $query_1 = $CrowdCode->add(array('shop_id'=>$shop_id,'item_id'=>$item_id,'expect_num'=>$expect_num,'codes_len'=>$len,'codes_i'=>$k,'codes'=>$codes,'codes_tmp'=>$codes));

        unset($codes);

    }

    $CountNum = $CountNum - (($num-1)*$len);

    $codes=array();

    for($i=1;$i<=$CountNum;$i++){

        $codes[$i]=10000000+$code_i;

        $code_i--;

    }shuffle($codes);$codes=serialize($codes);

    $query_2 = $CrowdCode->add(array('shop_id'=>$shop_id,'item_id'=>$item_id,'expect_num'=>$expect_num,'codes_len'=>$CountNum,'codes_i'=>$num,'codes'=>$codes,'codes_tmp'=>$codes));

    unset($codes);

    if($query_1 && $query_2) M('ItemCrowd')->where('shop_id = '.$shop_id.' AND item_id = '.$item_id.' AND expect_num = '.$expect_num.' AND status = 0')->setField('status',1);

    return $query_1 && $query_2;

}



/**

 * 计算商品折扣价

 *  

 */

function item_discount_price($price, $discount, $is_discount_price_round) {

    return sprintf("%.2f", round($price*$discount/10, ($is_discount_price_round && $discount < 10) ? 0 : 2));

}





/**

 * 手机号加*

 */

function star_mobile($mobile){

    return mb_substr($mobile,0,4,'utf8').'***'.mb_substr($mobile,-2,2,'utf8');

}



/**

 * 众筹订单状态

 *  

 * (0:未付款,１：已付款,2已发货,3:交易完成4:已退款)

 */

function get_collectorder_status($type){

    switch ($type) {

        case 0:

            $info = '未付款';

            break;

        case 1:

            $info = '已付款';

            break;

        case 2:

            $info = '已发货';

            break;

        case 3:

            $info = '交易完成';

            break;

        case 4:

            $info = '已退款';

            break;

        default:

            $info = '';

    }

    return $info;

}





/**

 * 记录店铺会员数

 *  

 */

function get_user_count($shop_id,$user_id){

    $user_count = S('shop_count_'.$shop_id);

    if(!$user_count){

        $user_count = M('User')->db(1, 'MASTER_DB')->where('shop_id = ' . $shop_id . ' AND is_user_del = 0 AND user_id <='.$user_id)->count(1);

        S('shop_count_'.$shop_id,$user_count,30*60);

    }else{

        S('shop_count_'.$shop_id,$user_count+1,30*60);

    }

}



/**

 * 微现场状态

 *  

 */

function get_live_status($type){

    switch ($type) {

        case 0:

            $info = '未开始';

            break;

        case 1:

            $info = '进行中';

            break;

        case 2:

            $info = '已结束';

            break;

        default:

            $info = '';

    }

    return $info;

}



/**

 * 清除静态缓存

 *  

 * @param $type int 类型(1:首页;2:商品列表页;3:商品详情页;4:文章列表页;5:文章详情页)

 * @param $suffix string 名称后缀

 */

function del_html_cache($type, $suffix=null) {

    switch ($type) {

        case 1:

            $name = 'Shop_index';

            break;

        case 2:

            $name = 'Item_lists';

            break;

        case 3:

            $name = 'Item_detail';

            break;

        case 4:

            $name = 'Magazine_lists';

            break;

        case 5:

            $name = 'Magazine_detail';

            break;

        default:

            $name = '';

    }

    if ($name) {

        $name .= SHOP_ID;

        if ($suffix) $name .= '_' . $suffix;

        S($name, null);

    }



}





/**

 * 微夺宝计算佣金

 *  

 */

function crow_calculition_commission($order_id){

    $OrderCrowd = D('OrderCrowd');

    $User = D('User');

    $UserDls = M('UserDls');

    $order_info = $OrderCrowd->db(1, 'MASTER_DB')

        ->where('order_crowd_id='.$order_id)

        -> field('create_time,shop_id,user_id,order_crowd_id,price,address_id,is_self_take,self_take_address')

        ->find();

    // 订单不存在!

    if(!$order_info){

        return false;

    }



    $shopId = intval($order_info['shop_id']);

    $user_info = $User->where('user_id='.$order_info['user_id'])

        ->field('superior_user_id,top_user_id,three_user_id,is_agent')

        ->find();

    $map = array(

        'shop_id'       => $shopId,

        'config_name'   => array('in', array('directly_online_ratio', 'superior_online_ratio', 'three_online_ratio'))

    );

    $config = D('Config') -> where($map)-> select();

    $default_ratio = array();



    // 是否开启分销内购

    $is_fenxiao_ins = config('is_fenxiao_ins', null, $shopId);

    if ($is_fenxiao_ins && $user_info['is_agent']) {

        // 成为分销商之前不能有佣金

        $mAgentTime = M('AgentTime');

        $agentTimeWhere = array(

            'user_id' => $order_info['user_id']

        );

        $agentUserInfo = $mAgentTime->where($agentTimeWhere)->find();

        if(!$agentUserInfo) {

            $user_info['three_user_id'] = $user_info['top_user_id'];

            $user_info['top_user_id'] = $user_info['superior_user_id'];

            $user_info['superior_user_id'] = $order_info['user_id'];

        } elseif($agentUserInfo['agent_time'] <= $order_info['create_time']){

            $user_info['three_user_id'] = $user_info['top_user_id'];

            $user_info['top_user_id'] = $user_info['superior_user_id'];

            $user_info['superior_user_id'] = $order_info['user_id'];

        }

    }

    // 代理商信息

    $dls_info = $UserDls->where('user_id = ' . $order_info['user_id'])->find();



    // 是否为区域代理

    $dls_mode = config('dls_mode', null, $shopId);

    if ($dls_mode == 1 || $dls_mode == 2) {

        if ($order_info['is_self_take'] && $order_info['self_take_address']) {

            $addr = explode(' ',$order_info['self_take_address']);

            $address_info['province_id'] = M('Province')->where('province_name = "'.$addr[0]."")->getField('province_id');

            $address_info['city_id'] = M('City')->where('city_name = "'.$addr[1]."")->getField('city_id');

            $address_info['area_id'] = M('Area')->where('area_name = "'.$addr[2]."")->getField('area_id');

        } else {

            $address_info = M('UserAddress')

                ->where(array('address_id' => $order_info['address_id']))

                ->field('province_id, city_id, area_id')

                ->find();

        }

        if ($address_info['province_id']) {

            // 省代

            $map = array(

                'shop_id'   => $shopId,

                'is_dls'    => 1,

                'dls_type'  => 1,

                'rank'      => 1,

                'region'    => array('like', '%'.$address_info['province_id'].'%')

            );

            $p_dls = $UserDls->where($map)->getField('user_id');

            if ($p_dls) $dls_info['superior_dls_id'] = $p_dls;

            elseif ($dls_mode == 2) $dls_info['superior_dls_id'] = null;

        }

        if ($address_info['city_id']) {

            // 市代

            $map = array(

                'shop_id'   => $shopId,

                'is_dls'    => 1,

                'dls_type'  => 1,

                'rank'      => 2,

                'region'    => array('like', '%'.$address_info['city_id'].'%')

            );

            $c_dls = $UserDls->where($map)->getField('user_id');

            if ($c_dls) $dls_info['top_dls_id'] = $c_dls;

            elseif ($dls_mode == 2) $dls_info['top_dls_id'] = null;

        }

        if ($address_info['area_id']) {

            // 区代

            $map = array(

                'shop_id'   => $shopId,

                'is_dls'    => 1,

                'dls_type'  => 1,

                'rank'      => 3,

                'region'    => array('like', '%'.$address_info['area_id'].'%')

            );

            $a_dls = $UserDls->where($map)->getField('user_id');

            if ($a_dls) $dls_info['three_dls_id'] = $a_dls;

            elseif ($dls_mode == 2) $dls_info['three_dls_id'] = null;

        }

    }





    $is_dls_fenxiao = config('is_dls_fenxiao', null, $shopId); // 代理商是否拿全民分销佣金



    if ($dls_info['four_dls_id']) {

        if (!$is_dls_fenxiao) {

            if ($dls_info['four_dls_id'] == $user_info['superior_user_id']) {

                $user_info['superior_user_id'] = null;

            } elseif ($dls_info['four_dls_id'] == $user_info['top_user_id']) {

                $user_info['top_user_id'] = null;

            } elseif ($dls_info['four_dls_id'] == $user_info['three_user_id']) {

                $user_info['three_user_id'] = null;

            }

        }



        $four_dls_ratio = $UserDls

            ->where(array('user_id'=>$dls_info['four_dls_id'], 'is_dls'=>1, 'rank'=>4))

            ->getField('ratio');

    }

    if ($dls_info['three_dls_id']) {

        if (!$is_dls_fenxiao) {

            if ($dls_info['three_dls_id'] == $user_info['superior_user_id']) {

                $user_info['superior_user_id'] = null;

            } elseif ($dls_info['three_dls_id'] == $user_info['top_user_id']) {

                $user_info['top_user_id'] = null;

            } elseif ($dls_info['three_dls_id'] == $user_info['three_user_id']) {

                $user_info['three_user_id'] = null;

            }

        }



        $three_dls_ratio = $UserDls

            ->where(array('user_id'=>$dls_info['three_dls_id'], 'is_dls'=>1, 'rank'=>3))

            ->getField('ratio');

    }

    if ($dls_info['top_dls_id']) {

        if (!$is_dls_fenxiao) {

            if ($dls_info['top_dls_id'] == $user_info['superior_user_id']) {

                $user_info['superior_user_id'] = null;

            } elseif ($dls_info['top_dls_id'] == $user_info['top_user_id']) {

                $user_info['top_user_id'] = null;

            } elseif ($dls_info['top_dls_id'] == $user_info['three_user_id']) {

                $user_info['three_user_id'] = null;

            }

        }



        $top_dls_ratio = $UserDls->where(array('user_id'=>$dls_info['top_dls_id'], 'is_dls'=>1, 'rank'=>2))

            ->getField('ratio');

        if ($three_dls_ratio) {

            $top_dls_ratio -= $three_dls_ratio;

            if ($top_dls_ratio < 0) $top_dls_ratio = 0;

        }

    }

    if ($dls_info['superior_dls_id']) {

        if (!$is_dls_fenxiao) {

            if ($dls_info['superior_dls_id'] == $user_info['superior_user_id']) {

                $user_info['superior_user_id'] = null;

            } elseif ($dls_info['superior_dls_id'] == $user_info['top_user_id']) {

                $user_info['top_user_id'] = null;

            } elseif ($dls_info['superior_dls_id'] == $user_info['three_user_id']) {

                $user_info['three_user_id'] = null;

            }

        }



        $superior_dls_ratio = $UserDls

            ->where(array('user_id'=>$dls_info['superior_dls_id'], 'is_dls'=>1, 'rank'=>1))

            ->getField('ratio');

        if (($top_dls_ratio + $three_dls_ratio) > 0) {

            $superior_dls_ratio -= ($top_dls_ratio + $three_dls_ratio);

            if ($superior_dls_ratio < 0) $superior_dls_ratio = 0;

        }

    }



    if($user_info && $order_info)

    {



        foreach($config as $rs){

            $default_ratio[$rs['config_name']] = $rs['config_value'];

        }

        $ratio = ratio_commission($user_info,$default_ratio);



        // 判断上线是否为分销商

        $is_superior_agent = 0;

        if($user_info['superior_user_id'] > 0){

            if ($User->where('user_id = ' . $user_info['superior_user_id'] . ' AND is_user_del = 0 AND shop_id = ' . $shopId)

                    ->getField('is_agent') == 1) {

                $is_superior_agent = 1;

            }

        }



        $is_top_agent = 0;

        if($user_info['top_user_id'] > 0){

            if ($User->where('user_id = ' . $user_info['top_user_id'] . ' AND is_user_del = 0 AND shop_id = ' . $shopId)

                    ->getField('is_agent') == 1) {

                $is_top_agent = 1;

            }

        }



        $is_three_agent = 0;

        if($user_info['three_user_id'] > 0){

            if ($User->where('user_id = ' . $user_info['three_user_id'] . ' AND is_user_del = 0 AND shop_id = ' . $shopId)

                    ->getField('is_agent') == 1) {

                $is_three_agent = 1;

            }

        }



        // 买家所属门店,员工

        $store_ratio = $staff_ratio = $store_id = $staff_id = 0;

        $store_info = M('UserStore')->where('user_id = ' . $order_info['user_id'])->find();

        if ($store_info) {

            $store_id = $store_info['store_id'];

            if ($store_id) {

                $agent_rank_id = M('User')->where(array('user_id'=>$store_id, 'is_agent'=>3))->getField('agent_rank_id');

                if ($agent_rank_id) {

                    $store_ratio = M('AgentRank')->where(array('agent_rank_id'=>$agent_rank_id, 'shop_id'=>$shopId, 'agent_type'=>3))->getField('superior_ratio');

                }

            }



            $staff_id = $store_info['staff_id'];

            if ($store_id) {

                $agent_rank_id = M('User')->where(array('user_id'=>$store_id, 'is_agent'=>2))->getField('agent_rank_id');

                if ($agent_rank_id) {
                    $staff_ratio = M('AgentRank')->where(array('agent_rank_id'=>$agent_rank_id, 'shop_id'=>$shopId, 'agent_type'=>2))->getField('superior_ratio');
                }

            }

        }
       


        $OrderCrowd->startTrans();

        // 分销商佣金计算

        $order_fx_money = $order_info['price'];

        if ($order_fx_money < 0) $order_fx_money = 0;

        //if ($order_dl_money < 0) $order_dl_money = 0;

        $payment_msg = '(宝贝价值('.$order_info['price'].')';

        $payment_msg .= ')';

        $superior_order_commission = $order_fx_money * ($ratio['directly_online_ratio'] / 100);

        $to_order_commission = $order_fx_money * ($ratio['superior_online_ratio'] / 100);

        $three_order_commission = $order_fx_money * ($ratio['three_online_ratio'] / 100);

        $superior_user_calculation = $payment_msg.' * 佣金比例('.($ratio['directly_online_ratio'] / 100).')';

        $top_user_calculation = $payment_msg.' * 佣金比例('.($ratio['superior_online_ratio'] / 100).')';

        $three_user_calculation = $payment_msg.' * 佣金比例('.($ratio['three_online_ratio'] / 100).')';



        // 代理商佣金计算

        $order_dl_money = $order_info['price'];

        if ($order_dl_money < 0) $order_dl_money = 0;



        $payment_dl_msg = '(宝贝价值('.$order_info['price'].')';

        $payment_dl_msg .= ')';

        // 代理商佣金

        if (isset($superior_dls_ratio)) $superior_dls_commission = $order_dl_money * ($superior_dls_ratio / 100);

        if (isset($top_dls_ratio)) $top_dls_commission = $order_dl_money * ($top_dls_ratio / 100);

        if (isset($three_dls_ratio)) $three_dls_commission = $order_dl_money * ($three_dls_ratio / 100);

        if (isset($four_dls_ratio)) $three_dls_commission = $order_dl_money * ($four_dls_ratio / 100);



        if (isset($superior_dls_ratio)) $superior_dls_calculation = $payment_dl_msg.' * 佣金比例('.($superior_dls_ratio / 100).')';

        if (isset($top_dls_ratio)) $top_dls_calculation = $payment_dl_msg.' * 佣金比例('.($top_dls_ratio / 100).')';

        if (isset($three_dls_ratio)) $three_dls_calculation = $payment_dl_msg.' * 佣金比例('.($three_dls_ratio / 100).')';

        if (isset($four_dls_ratio)) $three_dls_calculation = $payment_dl_msg.' * 佣金比例('.($four_dls_ratio / 100).')';





        // 计算门店和员工佣金

        if (($store_id && $store_ratio) || ($staff_id && $staff_ratio)){

            $payment_msg = '(宝贝价值('.$order_info['price'].')';

            $payment_msg .= ')';

            $store_commission = $order_fx_money * ($store_ratio / 100);

            $staff_commission = $order_fx_money * ($staff_ratio / 100);

            $store_calculation = $payment_msg.' * 佣金比例('.($store_ratio / 100).')';

            $staff_calculation = $payment_msg.' * 佣金比例('.($staff_ratio / 100).')';

        }



        $order_data = array();

        if($is_superior_agent){

            $order_data['superior_user_id'] = $user_info['superior_user_id'];

            $order_data['superior_commission'] = $superior_order_commission;

            $order_data['have_balance'] = 1;

            $order_data['superior_user_calculation'] = $superior_user_calculation;

        }

        if($is_top_agent){

            $order_data['top_user_id'] = $user_info['top_user_id'];

            $order_data['top_commission'] = $to_order_commission;

            $order_data['have_balance'] = 1;

            $order_data['top_user_calculation'] = $top_user_calculation;

        }

        if($is_three_agent){

            $order_data['three_user_id'] = $user_info['three_user_id'];

            $order_data['three_commission'] = $three_order_commission;

            $order_data['have_balance'] = 1;

            $order_data['three_user_calculation'] = $three_user_calculation;

        }



        // 代理商佣金

        if ($dls_info['superior_dls_id']) {

            if (!isset($superior_dls_commission)) $superior_dls_commission = 0;

            $order_data['superior_dls_id'] = $dls_info['superior_dls_id'];

            $order_data['superior_dls_commission'] = $superior_dls_commission;

            $order_data['have_balance'] = 1;

            $order_data['superior_dls_calculation'] = $superior_dls_calculation;

        }

        if ($dls_info['top_dls_id']) {

            if (!isset($top_dls_commission)) $top_dls_commission = 0;

            $order_data['top_dls_id'] = $dls_info['top_dls_id'];

            $order_data['top_dls_commission'] = $top_dls_commission;

            $order_data['have_balance'] = 1;

            $order_data['top_dls_calculation'] = $top_dls_calculation;

        }

        if ($dls_info['three_dls_id']) {

            if (!isset($three_dls_commission)) $three_dls_commission = 0;

            $order_data['three_dls_id'] = $dls_info['three_dls_id'];

            $order_data['three_dls_commission'] = $three_dls_commission;

            $order_data['have_balance'] = 1;

            $order_data['three_dls_calculation'] = $three_dls_calculation;

        }

        if ($dls_info['four_dls_id']) {

            if (!isset($four_dls_commission)) $four_dls_commission = 0;

            $order_data['four_dls_id'] = $dls_info['four_dls_id'];

            $order_data['four_dls_commission'] = $four_dls_commission;

            $order_data['have_balance'] = 1;

            $order_data['four_dls_calculation'] = $four_dls_calculation;

        }



        if ($store_id) {

            if (!isset($store_commission)) $store_commission = 0;

            $order_data['store_id'] = $store_id;

            $order_data['store_commission'] = $store_commission;

            $order_data['have_balance'] = 1;

            $order_data['store_calculation'] = $store_calculation;

        }



        if ($staff_id) {

            if (!isset($staff_commission)) $staff_commission = 0;

            $order_data['staff_id'] = $staff_id;

            $order_data['staff_commission'] = $staff_commission;

            $order_data['have_balance'] = 1;

            $order_data['staff_calculation'] = $staff_calculation;

        }

        $oid = $OrderCrowd -> where('order_crowd_id='.$order_id) -> save($order_data);

        if($oid === false){

            $OrderCrowd->rollback();

        }else{

            $OrderCrowd->commit();

            return true;

        }

    }

    return false;

}



/**

 * 是否复购

 *

 */

function is_repurchase($item_id,$user_id,$shop_id=SHOP_ID){

    $repurchase_info = M('ItemRepurchase')->where('item_id = '.$item_id.' AND shop_id = '.$shop_id)->find();

    if(!empty($repurchase_info) && $repurchase_info['repurchase_price'] !=0){

        $is_repurchase = config('is_repurchase',null,$shop_id);

        $is_buy_repurchase = config('is_buy_repurchase',null,$shop_id);

        if($is_repurchase){

            if($is_buy_repurchase){

                $re_map = array('o.user_id'=>$user_id,'o.dc_shop'=>$shop_id,'o.status'=>3);

            }else{

                $re_map = array('o.user_id'=>$user_id,'o.dc_shop'=>$shop_id,'o.status'=>3,'i.item_id'=>$item_id);

            }

        }

        else{

            if($is_buy_repurchase){

                $re_map = array('o.user_id'=>$user_id,'o.dc_shop'=>$shop_id,'o.status'=>array('in','1,2,3'));

            }else{

                $re_map = array('o.user_id'=>$user_id,'o.dc_shop'=>$shop_id,'o.status'=>array('in','1,2,3'),'i.item_id'=>$item_id);

            }

        }

//        $is_repurchase_order = M('Order')->alias('o')->join('__ORDER_ITEM__ as i on i.order_id = o.order_id')->where($re_map)->count(1);

        $is_repurchase_order = M('Order')->alias('o')->join('__ORDER_ITEM__ as i on i.order_id = o.order_id')->where($re_map)->count(1);

    }

    if($is_repurchase_order){

        return $repurchase_info;

    }else{

        return false;

    }

}



/**

 * 返回大数据的正整数，超9位的处理

 * @author panw

 */

function check_intval($val){

    if(is_numeric($val) && $val>0){

        return $val;

    }else{

        return 0;

    }

}





/**

 * RGB转 十六进制

 * @param $rgb RGB颜色的字符串 如：rgb(255,255,255);

 * @return string 十六进制颜色值 如：#FFFFFF

 */

function RGBToHex($rgb){

    $regexp = "/^rgb\(([0-9]{0,3})\,\s*([0-9]{0,3})\,\s*([0-9]{0,3})\)/";

    preg_match($regexp, $rgb, $match);

    array_shift($match);

    $hexColor = "0x";

    $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');

    for ($i = 0; $i < 3; $i++) {

        $r = null;

        $c = $match[$i];

        $hexAr = array();

        while ($c > 16) {

            $r = $c % 16;

            $c = ($c / 16) >> 0;

            array_push($hexAr, $hex[$r]);

        }

        array_push($hexAr, $hex[$c]);

        $ret = array_reverse($hexAr);

        $item = implode('', $ret);

        $item = strtolower(str_pad($item, 2, '0', STR_PAD_LEFT));

        $hexColor .= $item;

    }

    return $hexColor;

}



/**

 * 十六进制 转 RGB

 */

function hex2rgb($hexColor) {

    $color = str_replace('0x', '', $hexColor);

    if (strlen($color) > 3) {

        $rgb = array(

            'r' => hexdec(substr($color, 0, 2)),

            'g' => hexdec(substr($color, 2, 2)),

            'b' => hexdec(substr($color, 4, 2))

        );

    } else {

        $color = $hexColor;

        $r = substr($color, 0, 1) . substr($color, 0, 1);

        $g = substr($color, 1, 1) . substr($color, 1, 1);

        $b = substr($color, 2, 1) . substr($color, 2, 1);

        $rgb = array(

            'r' => hexdec($r),

            'g' => hexdec($g),

            'b' => hexdec($b)

        );

    }

    $result = "rgb($rgb[r],$rgb[g],$rgb[b])";

    return $result;

}



/*function bccomp($Num1,$Num2,$Scale=null) {

  // check if they're valid positive numbers, extract the whole numbers and decimals

  if(!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num1,$Tmp1)||

     !preg_match("/^\+?(\d+)(\.\d+)?$/",$Num2,$Tmp2)) return('0');



  // remove leading zeroes from whole numbers

  $Num1=ltrim($Tmp1[1],'0');

  $Num2=ltrim($Tmp2[1],'0');



  // first, we can just check the lengths of the numbers, this can help save processing time

  // if $Num1 is longer than $Num2, return 1.. vice versa with the next step.

  if(strlen($Num1)>strlen($Num2)) return(1);

  else {

    if(strlen($Num1)<strlen($Num2)) return(-1);



    // if the two numbers are of equal length, we check digit-by-digit

    else {



      // remove ending zeroes from decimals and remove point

      $Dec1=isset($Tmp1[2])?rtrim(substr($Tmp1[2],1),'0'):'';

      $Dec2=isset($Tmp2[2])?rtrim(substr($Tmp2[2],1),'0'):'';



      // if the user defined $Scale, then make sure we use that only

      if($Scale!=null) {

        $Dec1=substr($Dec1,0,$Scale);

        $Dec2=substr($Dec2,0,$Scale);

      }

      // calculate the longest length of decimals

      $DLen=max(strlen($Dec1),strlen($Dec2));



      // append the padded decimals onto the end of the whole numbers

      $Num1.=str_pad($Dec1,$DLen,'0');

      $Num2.=str_pad($Dec2,$DLen,'0');



      // check digit-by-digit, if they have a difference, return 1 or -1 (greater/lower than)

      for($i=0;$i<strlen($Num1);$i++) {

        if((int)$Num1{$i}>(int)$Num2{$i}) return(1);

        else

          if((int)$Num1{$i}<(int)$Num2{$i}) return(-1);

      }



      // if the two numbers have no difference (they're the same).. return 0

      return(0);

    }

  }  

}*/





    /**

     * 获取紧缩月底时间

     * @param $uid 当前用户id 

     * @return string  上级分销商id 

     * @author lius

     */



    function get_end_month($date,$m=0){

        $BeginDate=date('Y-m-01', strtotime($date));// 获取当前月份第一天

        $m+=1;

        return date('Y-m-d', strtotime("$BeginDate +$m month -1 day"));

    }

    /**

     * 获取紧缩月初时间

     * @param $uid 当前用户id 

     * @return string  上级分销商id 

     * @author lius

     */



    function get_sta_month($date,$m=0){

        // $m+=1;

        // 获取当前月份第一天

        return date('Y-m-01', strtotime("$date +$m month"));//date('Y-m-d', strtotime("$BeginDate +$m month -1 day"));

    }

    /**

     * 获取城市id对应的名称

     * @param $aid 当前地区id 

     * @return string  对应的表 

     * @author lius

     */



    function get_area_name($aid,$m=1){

        switch ($m) {

            case 1:

                $aname = M('Province')->where('province_id='.$aid)->getField('province_name');

                break;

            case 2:

                $aname = M('City')->where('city_id='.$aid)->getField('city_name');

                break;

            case 3:

                $aname = M('Area')->where('area_id='.$aid)->getField('area_name');

                break;

            case 4:

                $aname = M('Town')->where('town_id='.$aid)->getField('town_name');

                break;

            default:

                $aname = M('Province')->where('province_id='.$aid)->getField('province_name');

                break;

        }

        return $aname;

    }

//统一的登录接口
function login_cookie($user,$last_time,$shop_id,$n=2){
    /* 记录登录cookie */
    if(is_numeric($user)){
        $user = D('User')->where(array('user_id'=>$user))->find();
    }
    $auth = array(
        'uid'       => $user['user_id'],
        'last_time' => $last_time,
        'shop_id'   => $shop_id,
        'status' => $user['status']
    );

    cookie('user_auth', $auth, $n*30*24*3600);
    cookie('user_auth_sign', data_auth_sign($auth), $n*30*24*3600);
    cookie('shop_id', $shop_id);
}

function getGroupLists(){
    //$group_lists = S('group_lists');
   // if ($group_lists === false) {
        $array = array(
            'shop_id'=>SHOP_ID,
        );
        $groupModels = M('Group')->field('group_id,title')->where($array)->order('group_id asc')->cache(true, 300)->select();
        foreach ($groupModels as $k=>$rs){
            $group_lists[] = array('group_id'=>$rs['group_id'],'title'=>$rs['title']);
        }
        S('group_lists', $group_lists, 30*86400);
    //}
    return $group_lists;
}
function getGroupArr(){
    $group_lists = S('group_arr');
    if ($group_lists === false) {
        $array = array(
            'shop_id'=>SHOP_ID,
        );
        $groupModels = M('Group')->field('group_id,title')->where($array)->order('group_id asc')->cache(true, 300)->select();
        foreach ($groupModels as $k=>$rs){
            $group_lists[$rs['group_id']] = $rs['title'];
        }
        S('group_arr', $group_lists, 30*86400);
    }
    return $group_lists;
}
function getGroupName($item_id){
    $k = 'ItemGroupNameBy'.$item_id;
    $title = S($k);
    if (empty($title)) {
        $model = M('ItemGroup')
            ->alias("t")
            ->join(" LEFT JOIN tp_group i ON i.group_id = t.group_id",'left')
            ->field('title')
            ->where(array(
                'i.title'=>array('like',"%区"),
                'shop_id'=>SHOP_ID,
                't.item_id'=>$item_id,
            ))
            ->find();
        if($model){
            $title = $model['title'];
            S($k, $title, 3600*24*7);
        }else{
            $title = '';
        }
    }
    return $title;
}

function getGroupSpan($str){
     $html = ' <span class="seckill">'.$str.'</span>';
    return $html;
}
function bx_var_dump($a){
    header("Content-Type: text/html; charset=utf8");
    var_dump($a);
    exit;
}
function get_self_address_order($user_id,$shop_id){

/*
 SELECT o.order_id,o.payment,o.status
FROM tp_order o
INNER JOIN tp_self_address as sd ON sd.self_address_id = o.self_address_id
INNER JOIN tp_order_item as i ON i.order_id = o.order_id
INNER JOIN tp_item_group as g ON i.item_id = g.item_id

WHERE o.dc_shop = '1' AND o.status = 3 AND sd.type_id = 1117 and g.group_id in(17,80,77);
GROUP BY o.order_id
*/
    $models = M('Order')
        ->alias("o")
        ->join(array("__SELF_ADDRESS__ as sd ON sd.self_address_id = o.self_address_id","__ORDER_ITEM__ as i ON i.order_id = o.order_id ","__ITEM_GROUP__ as g ON i.item_id = g.item_id"))
        ->field('o.order_id,o.payment,o.status')
        ->where(array(
            'o.dc_shop'=>$shop_id,
            'g.group_id'=>array('in',array(17,77,80)),
            'o.status'=>3,
            'sd.type_id'=>$user_id,
        ))
        ->group('o.order_id')
        ->select();
        //bx_var_dump(M('Order')->getLastSql());
    $runArr = array('count'=>0,'total'=>0);
    foreach ($models as $rs){
        $runArr['count']++;
        $runArr['total'] += $rs['payment'];
    }
    return $runArr;
}

function getYeji($user_id,$time,$end_time,$p_id = 0){
    /*
 SELECT u.user_id,o.order_id,i.current_price,i.consume_up,o.payment,o.end_time,from_unixtime(o.end_time,'%Y-%m-%d') from tp_user as u
left JOIN tp_order as o on u.user_id = o.user_id
left JOIN tp_order_item as i on i.order_id= o.order_id


where u.user_id = 62091 and o.`status` = 3 and i.consume_up = 1 and o.is_general = 0 and o.funds = 0 and o.payment > 0

     */
    if($time == 0){
        //$time = strtotime("2018-05-06 12:00:00");//累积开始时间为2018年5月28日
        $time = strtotime("2018-02-17 12:00:00");
    }

    $where = array(
        'o.status' =>array('in',array(1,3)),
        //'i.consume_up'=>1,
        'it.gift_bag' => 1,
        'o.is_general'=>0,
        'o.funds'=>0,
        'o.end_time'=>array('between',array($time,$end_time)),
    );
    if($p_id == 0) {

        $where['u.user_id'] = $user_id;


    }else{
        //AND (superior_user_id='.$user_id.' OR top_user_id='.$user_id .' OR three_user_id='.$user_id.')'
        //$where['_query'] = '(superior_user_id='.$p_id.' OR top_user_id='.$p_id .' OR three_user_id='.$p_id.')status=1&score=100&_logic=or';
        $map['u.superior_user_id']  = $p_id;
        $map['u.top_user_id'] = $p_id;
        $map['u.three_user_id'] = $p_id;
        $map['_logic'] = 'or';
        $where['_complex'] = $map;
    }

    $rs = M('User')
        ->alias("u")
        ->join(array("__ORDER__ as o ON u.user_id = o.user_id","__ORDER_ITEM__ as i ON i.order_id = o.order_id ",
            "__ITEM__ as it ON i.item_id = it.item_id"))
        ->where($where)
        //->sum('o.payment');
        ->sum('i.current_price*i.num');

    //var_dump(M('User')->getLastSql());
    //exit;

    return empty($rs)?0:$rs;

}

function get_agency_consume_by_pid($p_id){
    $map['u.superior_user_id']  = $p_id;
    $map['u.top_user_id'] = $p_id;
    $map['u.three_user_id'] = $p_id;
    $map['_logic'] = 'or';
    $where['_complex'] = $map;

    $rs = M('User')
        ->alias("u")
        ->where($where)
        ->sum('agency_consume');
    return empty($rs)?0:$rs;
}